jack | generating fully functional Java database models from Ruby | Database library
kandi X-RAY | jack Summary
Support
Quality
Security
License
Reuse
- Translates a string
- Fills the input buffer with new input
- Reports an error
- Tokenizes the scanner
- Load database connection configuration from environment
- Fetch yaml from given reader provider
- Load optional from map
- Find by foreign key
- Find instances by foreign key
- Deletes all tables
- Returns a summary for the query
- Returns a hashCode of this enum instance
- Creates the IN SQL statement
- Creates SQL statement
- Returns true if the table is empty
- Gets a connection to a database
- Add a sub record s sub record ids
- Returns a list of values for the given key
- Executes the update
- Executes an SQL query
- Fetch records from database
- Returns a summary of the transaction metrics
- Realizes the creation of the database
- Gets a connection from the pool
- Gets value
- Associates the specified value with the specified key
jack Key Features
jack Examples and Code Snippets
# This is the class path where you want the top-level generated code to go. databases_namespace: com.rapleaf.jack.test_project # Here, we define each of the separate databases for which Jack should # generate code. Each database is roughly equivalent to a Rails project. databases: - # The root namespace for this database. It's nice, but not required, to # have this be a subpackage of the 'databases_namespace'. root_namespace: com.rapleaf.jack.test_project.database_1 # What do you want to call this database? Leave out the "_production". db_name: Database1 # The path to the schema.rb in your Rails project. schema_rb: database_1/db/schema.rb # The path to the app/models dir in your Rails project. models: database_1/app/models # Tables to be ignored. No code will be generated for them. ignored_tables: table_1 table_2 - root_namespace: com.rapleaf.jack.test_project.database_2 db_name: Database2 schema_rb: database_2/db/schema.rb models: database_2/app/models
/all_my_databases /project.yml /rails_project_1 /rails_project_2 /ruby_project_that_uses_rails_project_2 /include/rails_project_2 # <= svn external to /all_my_databases/rails_project_2
def is_face_card(self): """Jack = 11, Queen = 12, King = 13""" return True if 10 < self._value <= 13 else False
def __init__(self, value, suit): super(BlackJackCard, self).__init__(value, suit)
Trending Discussions on jack
Trending Discussions on jack
QUESTION
I'm trying to write a regular expression that needs to return every tag name, attribute name, and attribute value
Here is the code example
Hello, My name is Jack, This is my selfie:
[img id='4' src="imageurl"]
Below is the quick-link to my profile
[profile username='jackisbest']
I need to get any text enclosed in [ ]
Also I need javascript regex to parse them and match them this way
> Match 1: img
> Match 2: id='4'
Group 1: id
Group 2: 4
> Match 3: src="imageurl"
Group 1: src
Group 2: imageurl
This is the regex I am using, but it can only match attributes and value
(\S+)=["']?((?:.(?!["']?\s+(?:\S+)=|[>"']))+.)["']
Thanks!!
ANSWER
Answered 2022-Feb-10 at 06:05I modified your regex to catch the tag name and used named capture groups.
/\[?(?\w+)\s?(?\S+)=['"]?(?(?:.(?!["']?\s+(?:\S+)=|[>"']))+.)["']/gm
This might work for you.
Test here: https://regex101.com/r/kT7pG4/1
QUESTION
I am trying to define a type where the favoriteFruit property's value must be an item in options array. Where the options array is dynamic/unknown (making it impossible to use union types "|").
const options = ["apple", "orange", "kiwi"]; // Dynamic list that can be modified in the future
type Person = {
name: string;
favoriteFruit: /* --- val in [...options] --- */
};
const personA:Person = {name: "Jack", favoriteFruit: "apple"}; // OK
const personB:Person = {name: "John", favoriteFruit: "orange"}; // OK
const personC:Person = {name: "Jane", favoriteFruit: "banana"}; // ERROR
ANSWER
Answered 2022-Feb-05 at 15:23I found this : How to convert array of strings to typescript types? .
const arr = ["foo", "bar", "loo"] as const
type arrTyp = typeof arr[number]; // "foo" | "bar" | "loo"
QUESTION
I have a list of names 'pattern' that I wish to match with strings in column 'url_text'. If there is a match i.e. True
the name should be printed in a new column 'pol_names_block' and if False
leave the row empty.
pattern = '|'.join(pol_names_list)
print(pattern)
'Jon Kyl|Doug Jones|Tim Kaine|Lindsey Graham|Cory Booker|Kamala Harris|Orrin Hatch|Bernie Sanders|Thom Tillis|Jerry Moran|Shelly Moore Capito|Maggie Hassan|Tom Carper|Martin Heinrich|Steve Daines|Pat Toomey|Todd Young|Bill Nelson|John Barrasso|Chris Murphy|Mike Rounds|Mike Crapo|John Thune|John. McCain|Susan Collins|Patty Murray|Dianne Feinstein|Claire McCaskill|Lamar Alexander|Jack Reed|Chuck Grassley|Catherine Masto|Pat Roberts|Ben Cardin|Dean Heller|Ron Wyden|Dick Durbin|Jeanne Shaheen|Tammy Duckworth|Sheldon Whitehouse|Tom Cotton|Sherrod Brown|Bob Corker|Tom Udall|Mitch McConnell|James Lankford|Ted Cruz|Mike Enzi|Gary Peters|Jeff Flake|Johnny Isakson|Jim Inhofe|Lindsey Graham|Marco Rubio|Angus King|Kirsten Gillibrand|Bob Casey|Chris Van Hollen|Thad Cochran|Richard Burr|Rob Portman|Jon Tester|Bob Menendez|John Boozman|Mazie Hirono|Joe Manchin|Deb Fischer|Michael Bennet|Debbie Stabenow|Ben Sasse|Brian Schatz|Jim Risch|Mike Lee|Elizabeth Warren|Richard Blumenthal|David Perdue|Al Franken|Bill Cassidy|Cory Gardner|Lisa Murkowski|Maria Cantwell|Tammy Baldwin|Joe Donnelly|Roger Wicker|Amy Klobuchar|Joel Heitkamp|Joni Ernst|Chris Coons|Mark Warner|John Cornyn|Ron Johnson|Patrick Leahy|Chuck Schumer|John Kennedy|Jeff Merkley|Roy Blunt|Richard Shelby|John Hoeven|Rand Paul|Dan Sullivan|Tim Scott|Ed Markey'
I am using the following code df['url_text'].str.contains(pattern)
which results in True
in case a name in 'pattern' is present in a row in column 'url_text' and False
otherwise. With that I have tried the following code:
df['pol_name_block'] = df.apply(
lambda row: pol_names_list if df['url_text'].str.contains(pattern) in row['url_text'] else ' ',
axis=1
)
I get the error:
TypeError: 'in ' requires string as left operand, not Series
ANSWER
Answered 2022-Jan-04 at 13:36From this toy Dataframe :
>>> import pandas as pd
>>> from io import StringIO
>>> df = pd.read_csv(StringIO("""
... id,url_text
... 1,Tim Kaine
... 2,Tim Kain
... 3,Tim
... 4,Lindsey Graham.com
... """), sep=',')
>>> df
id url_text
0 1 Tim Kaine
1 2 Tim Kain
2 3 Tim
3 4 Lindsey Graham.com
From pol_names_list
, we build patterns
by formating it like so :
patterns = '(%s)' % '|'.join(pol_names_list)
Then, we can use the extract
method to assign the value to the column pol_name_block
to get the expected result :
df['pol_name_block'] = df['url_text'].str.extract(patterns)
Output :
id url_text pol_name_block
0 1 Tim Kaine Tim Kaine
1 2 Tim Kain NaN
2 3 Tim NaN
3 4 Lindsey Graham.com Lindsey Graham
QUESTION
My code is very simple; I have an outlet to a UIButton, button
, and I am setting its image in code:
let jack = UIImage(named:"jack.png")
self.button.setImage(jack, for:.normal)
The problem is that this is not behaving as I expect. I expect the button image to be sized down to the button size, and I expect it to be a template image (tinted with the inherited tint color). Instead, I'm seeing the original image and it is full-sized. Is this a change in iOS 15?
It seems to be, because if I set my project's deployment target to iOS 14 and run it on an iOS 14 simulator, I do get the behavior that I expect.
ANSWER
Answered 2021-Oct-04 at 17:26Is this a change in iOS 15?
Yes and no. There is indeed a change in iOS 15, but the reason for the problem you're experiencing is a change in Xcode 13.
The change in iOS 15 is that there's a whole new way of configuring a button. This starts with giving the button one of four new iOS 15 types: Plain, Gray, Tinted, and Filled. If you set your button to have any of those types, you are opting in to the new behavior.
The problem you're seeing is because, in Xcode 13, when you make a button in the storyboard, it does give the button one of those types: Plain. So you have opted into the new dispensation without knowing it!
The solution, if you want the old behavior, is to change the Style pop-up menu (in the Attributes inspector) from Plain to Default. Now you have an old-style button and it will behave in the way you're accustomed to.
(Of course, in the long run, you're going to want to adopt the new dispensation. I'm just explaining the apparent change in behavior.)
QUESTION
Assume we have two tables (think as in SQL tables), where the primary key in one of them is the foreign key in the other. I'm supposed to write a simple algorithm that would imitate the joining of these two tables. I thought about iterating over each element in the primary key column in the first table, having a second loop where it checks if the foreign key matches, then store it in an external array or list. However, this would take O(N*M) and I need to find something better. There is a hint in the textbook that it involves hashing, however, I'm not sure how hashing could be implemented here or how it would make it better?
Editing to add an example:
Table Employees
|ID (Primary Key)| Name | Department|
|:---------------|:----:|----------:|
| 1 | Jack | IT |
| 2 | Amy | Finance |
Table Transactions
|Sold Product| Sold By(Foreign Key)| Sold To|
|:-----------|:-------------------:|-------:|
| TV | 1 | Mary |
| Radio | 1 | Bob |
| Mobile | 2 | Lisa |
What I want to do is write an algorithm that joins these two tables using hashing, and not anything complex, just a simple idea on how to do that.
ANSWER
Answered 2021-Dec-24 at 22:18Read the child table's primary and foreign keys into a map where the keys are the foreign keys and the values are the primary keys. Keep in mind that one foreign key can map to multiple primary keys if this is a one to many relationship.
Now iterate over the primary keys of the mother table and for each primary key check whether it exists in the map. If so, you add a tuple of the primary keys of the rows that have a relation to the array (or however you want to save it).
The time complexity is O(n + m)
. Iterate over the rows of each table once. Since the lookup in the map is constant, we don't need to add it.
Space complexity is O(m)
where m
is the number of rows in the child table. This is some additional space you use in comparison to the naive solution to improve the time complexity.
QUESTION
Using the dataframe I want to create a new one which will contain Zip, Name and a column named Count which will include the count of Name per Zip.
Zip<-c("123245","12345","123245","123456","123456","12345")
Name<-c("Bob","Bob","Bob","Jack","Jack","Mary"),
df<-data.frame(Zip,Name,Name2)
library(dplyr)
df %>%
group_by(Zip) %>%
mutate(Name = cumsum(Name))
expected
Zip Name Count
1 123245 Bob 2
2 12345 Bob 1
3 12345 Mary 1
4 123456 Jack 2
ANSWER
Answered 2021-Dec-21 at 23:23Does this solve your problem?
Zip<-c("123245","12345","123245","123456","123456","12345")
Name<-c("Bob","Bob","Bob","Jack","Jack","Mary")
df<-data.frame(Zip,Name)
library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#> filter, lag
#> The following objects are masked from 'package:base':
#>
#> intersect, setdiff, setequal, union
df %>%
group_by(Zip, Name) %>%
summarise(Count = n())
#> `summarise()` has grouped output by 'Zip'. You can override using the `.groups` argument.
#> # A tibble: 4 × 3
#> # Groups: Zip [3]
#> Zip Name Count
#>
#> 1 123245 Bob 2
#> 2 12345 Bob 1
#> 3 12345 Mary 1
#> 4 123456 Jack 2
library(tidyverse)
library(microbenchmark)
Zip<-c("123245","12345","123245","123456","123456","12345")
Name<-c("Bob","Bob","Bob","Jack","Jack","Mary")
df<-data.frame(Zip,Name)
JM <- function(df){
df %>%
group_by(Zip, Name) %>%
summarise(Count = n())
}
JM(df)
#> `summarise()` has grouped output by 'Zip'. You can override using the `.groups` argument.
#> # A tibble: 4 × 3
#> # Groups: Zip [3]
#> Zip Name Count
#>
#> 1 123245 Bob 2
#> 2 12345 Bob 1
#> 3 12345 Mary 1
#> 4 123456 Jack 2
TarJae <- function(df){
df %>%
count(Zip, Name, name= "Count")
}
TIC <- function(df){
aggregate(cbind(Count = Zip) ~ Zip + Name, df, length)
}
TIC(df)
#> Zip Name Count
#> 1 123245 Bob 2
#> 2 12345 Bob 1
#> 3 123456 Jack 2
#> 4 12345 Mary 1
res <- microbenchmark(JM(df), TIC(df), TarJae(df))
autoplot(res)
#> Coordinate system already present. Adding new coordinate system, which will replace the existing one.
Created on 2021-12-22 by the reprex package (v2.0.1)
QUESTION
I tried stopping the column overflow with max-height, max-width, but it doesn't seem to work.
I've made three columns with CSS Grid. One for the nav section, one for the left column and one for the right column. the left column section keeps overflowing over the nav section and the right column section as shown in the screenshots.
What I'm trying to achieve:
What happens:
@import url("https://fonts.googleapis.com/css2?family=Asap:wght@400;700&display=swap");
* {
padding: 0;
margin: 0;
height: 100%;
width: 100%;
background-color: #4a6163;
font-family: "Asap";
-webkit-box-sizing: border-box;
box-sizing: border-box;
}
.main_grid {
display: -ms-grid;
display: grid;
-ms-grid-columns: 0.25fr (1fr)[2];
grid-template-columns: 0.25fr repeat(2, 1fr);
-ms-grid-rows: 1fr;
grid-template-rows: 1fr;
grid-column-gap: 0px;
grid-row-gap: 0px;
max-height: 100%;
max-width: 100%;
}
.nav_section {
-ms-grid-row: 1;
-ms-grid-column: 1;
-ms-grid-column-span: 1;
grid-area: 1 / 1 / 1 / 2;
border: 3px yellow solid;
}
.left_column {
-ms-grid-row: 1;
-ms-grid-column: 2;
-ms-grid-column-span: 1;
grid-area: 1 / 2 / 1 / 3;
border: 1px yellow solid;
}
.right_colomn {
-ms-grid-row: 1;
-ms-grid-column: 3;
-ms-grid-column-span: 1;
grid-area: 1 / 3 / 1 / 4;
border: 2px blue solid;
}
.left_column > h1 {
font-family: "Asap";
color: #f9faf4;
font-size: 13rem;
font-style: normal;
font-weight: normal;
line-height: 15.75rem;
text-transform: uppercase;
-webkit-transform: rotate(-90deg);
transform: rotate(-90deg);
display: -webkit-box;
display: -ms-flexbox;
display: flex;
border: red 3px solid;
-o-object-fit: contain;
object-fit: contain;
max-width: 100%;
max-height: 100%;
}
.main_bio {
color: #f2c4ce;
font-size: 1.75rem;
text-decoration: underline;
}
ANSWER
Answered 2021-Dec-18 at 21:12To avoid overflowing, you can use the rule white-space: nowrap;
for your h1
. However, that will avoid breaking the line after "Hello," as well.
So I would also recommend adding a
after the Hello,
for explicitly breaking that line.
That should solve your line-break issues, but I noticed you're also rotating the text by 90deg
, and that can mess up the heading fitting inside the cell.
So I recommend adding the rule writing-mode: tb-rl
(link) to make the text be written vertically, and then rotating it 180deg instead of 90 (so it becomes bottom-up instead of top-down)
This is your snippet with the suggested changes
@import url("https://fonts.googleapis.com/css2?family=Asap:wght@400;700&display=swap");
* {
padding: 0;
margin: 0;
height: 100%;
width: 100%;
background-color: #4a6163;
font-family: "Asap";
-webkit-box-sizing: border-box;
box-sizing: border-box;
}
.main_grid {
display: -ms-grid;
display: grid;
-ms-grid-columns: 0.25fr (1fr)[2];
grid-template-columns: 0.25fr repeat(2, 1fr);
-ms-grid-rows: 1fr;
grid-template-rows: 1fr;
grid-column-gap: 0px;
grid-row-gap: 0px;
max-height: 100%;
max-width: 100%;
}
.nav_section {
-ms-grid-row: 1;
-ms-grid-column: 1;
-ms-grid-column-span: 1;
grid-area: 1 / 1 / 1 / 2;
border: 3px yellow solid;
}
.left_column {
-ms-grid-row: 1;
-ms-grid-column: 2;
-ms-grid-column-span: 1;
grid-area: 1 / 2 / 1 / 3;
border: 1px yellow solid;
}
.right_colomn {
-ms-grid-row: 1;
-ms-grid-column: 3;
-ms-grid-column-span: 1;
grid-area: 1 / 3 / 1 / 4;
border: 2px blue solid;
}
.left_column > h1 {
font-family: "Asap";
color: #f9faf4;
font-size: 13rem;
font-style: normal;
font-weight: normal;
line-height: 15.75rem;
text-transform: uppercase;
/* Updated the following 3 lines */
white-space: nowrap;
writing-mode: tb-rl;
-webkit-transform: rotate(-180deg);
transform: rotate(-180deg);
display: -webkit-box;
display: -ms-flexbox;
display: flex;
border: red 3px solid;
-o-object-fit: contain;
object-fit: contain;
max-width: 100%;
max-height: 100%;
}
.main_bio {
color: #f2c4ce;
font-size: 1.75rem;
text-decoration: underline;
}
QUESTION
I am trying to setup a SwiftUI .contextMenu
with a button that toggle a Bool
value. The context menu's button text is supposed to change when the Bool
toggles. But the context menu doesn't update. Is there a way to force update the context menu?
Sample code depicting the issue:
import SwiftUI
struct Item: Identifiable {
let id = UUID()
let user: String
var active: Bool
}
struct ContentView: View {
@State var items: [Item] = [
Item(user: "Daniel",active: false),
Item(user: "Jack", active: true),
Item(user: "John", active: true)
]
@State var isOn : Bool = false
var body: some View {
List {
ForEach(items) { item in
VStack {
Text("\(item.user)")
HStack {
Text("Active ? ")
Text(item.active ? "YES": "NO")
}
}.contextMenu{
Button(action: {
let index = items.firstIndex{$0.user == item.user}
items[index!].active.toggle()
}) {
Text(item.active ? "Set as Active": "Set as Inactive")
}
}
}
}
}
}
ANSWER
Answered 2021-Nov-29 at 18:53It's a bug in SwiftUI, and it is still broken in the simulator of Xcode 13.2 beta 2.
I managed to work around it by duplicating the list item in both branches of an if item.active
statement, like this:
struct ContentView: View {
@State var items: [Item] = [
Item(user: "Daniel",active: false),
Item(user: "Jack", active: true),
Item(user: "John", active: true)
]
var body: some View {
List {
ForEach(items) { item in
// work around SwiftUI bug where
// context menu doesn't update
if item.active { listItem(for: item) }
else { listItem(for: item) }
}
}
}
private func listItem(for item: Item) -> some View {
VStack {
Text("\(item.user)")
HStack {
Text("Active ? ")
Text(item.active ? "YES": "NO")
}
}
.contextMenu {
Button(item.active ? "Deactivate" : "Activate") {
if let index = items.firstIndex(where: { $0.id == item.id }) {
items[index].active.toggle()
}
}
}
.id(item.id)
}
}
QUESTION
I have the following dataframes (df11 and df22) I'd like to do a merge/full join on with "UserID=UserID" and date difference <= 30 . So if the UserIDs match up AND the date's are less than or equal to 30, I'd like them merged into one singular row. I've looked at fuzzy join here and sqldf here but I can't figure out how to implement either of those for my data frames.
df1 <- structure(list(UserID = c(1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L),
Full.Name = c( "John Smith", "Jack Peters", "Bob Brown", "Jane Doe", "Jackie Jane", "Sarah Brown", "Chloe Brown", "John Smith" ),
Info = c("yes", "no", "yes", "yes", "yes", "yes", "no", "yes"),
EncounterID = c(13L, 14L, 15L, 16L, 17L, 18L, 19L, 13L), DateTime = c("1/2/21 00:00", "1/5/21 12:00", "1/1/21 1:31", "1/5/21 3:34", "5/9/21 5:33", "5/8/21 3:39", "12/12/21 2:30", "12/11/21 9:21"),
Temp = c("100", "103", "104", "103", "101", "102", "103", "105"),
misc = c("(null)", "no", "(null)", "(null)", "(null)","(null)", "(null)", "(null)"
)),
class = "data.frame", row.names = c(NA,
-8L))
df2 <- structure(list(UserID = c(1L, 2L, 3L, 4L, 5L, 6L),
Full.Name = c("John Smith", "Jack Peters", "Bob Brown", "Jane Doe", "Jackie Jane", "Sarah Brown"),
DOB = c("1/1/90", "1/10/90", "1/2/90", "2/20/80", "2/2/80", "12/2/80"),
EncounterID = c(13L, 14L, 15L, 16L, 17L, 18L), EncounterDate = c("1/1/21", "1/2/21", "1/1/21", "1/6/21", "5/7/21", "5/8/21"),
Type = c("Intro", "Intro", "Intro", "Intro", "Care", "Out"),
responses = c("(null)", "no",
"yes", "no", "no", "unsat")),
class = "data.frame", row.names = c(NA,
-6L))
loadedNamespaces()
install.packages("Rcpp")
library(dplyr)
library(tidyr)
install.packages("lubridate")
library(lubridate)
df11 <-
df1 %>%
separate(DateTime, c("Date", "Time"), sep=" ") %>%
mutate(Date = as_datetime(mdy(Date))) %>%
select(-Time) %>%
as_tibble()
df22 <-
df2 %>%
mutate(across(c(EncounterDate), mdy)) %>%
mutate(across(c(EncounterDate), as_datetime)) %>%
as_tibble()
@r2evans After running the first set of code, I get the following output. Which is slightly different from yours.
df11 <- mutate(df11, Date_m30 = Date %m-% days(30), Date_p30 = Date %m+% days(30))
df11
# A tibble: 8 x 7
UserID Full.Name Info EncounterID Date Temp misc
1 1 John Smith yes 13 2021-01-02 00:00:00 100 (null)
2 2 Jack Peters no 14 2021-01-05 00:00:00 103 no
3 3 Bob Brown yes 15 2021-01-01 00:00:00 104 (null)
4 4 Jane Doe yes 16 2021-01-05 00:00:00 103 (null)
5 5 Jackie Jane yes 17 2021-05-09 00:00:00 101 (null)
6 6 Sarah Brown yes 18 2021-05-08 00:00:00 102 (null)
7 7 Chloe Brown no 19 2021-12-12 00:00:00 103 (null)
8 1 John Smith yes 13 2021-12-11 00:00:00 105 (null)
ANSWER
Answered 2021-Nov-05 at 17:59One way is to first create "+/- 30 day" columns in one of them, then do a standard date-range join. Using sqldf
:
Prep:
library(dplyr)
df11 <- mutate(df11, Date_m30 = Date %m-% days(30), Date_p30 = Date %m+% days(30))
df11
# # A tibble: 8 x 9
# UserID Full.Name Info EncounterID Date Temp misc Date_m30 Date_p30
#
# 1 1 John Smith yes 13 2021-01-02 00:00:00 100 (null) 2020-12-03 00:00:00 2021-02-01 00:00:00
# 2 2 Jack Peters no 14 2021-01-05 00:00:00 103 no 2020-12-06 00:00:00 2021-02-04 00:00:00
# 3 3 Bob Brown yes 15 2021-01-01 00:00:00 104 (null) 2020-12-02 00:00:00 2021-01-31 00:00:00
# 4 4 Jane Doe yes 16 2021-01-05 00:00:00 103 (null) 2020-12-06 00:00:00 2021-02-04 00:00:00
# 5 5 Jackie Jane yes 17 2021-05-09 00:00:00 101 (null) 2021-04-09 00:00:00 2021-06-08 00:00:00
# 6 6 Sarah Brown yes 18 2021-05-08 00:00:00 102 (null) 2021-04-08 00:00:00 2021-06-07 00:00:00
# 7 7 Chloe Brown no 19 2021-12-12 00:00:00 103 (null) 2021-11-12 00:00:00 2022-01-11 00:00:00
# 8 1 John Smith yes 13 2021-12-11 00:00:00 105 (null) 2021-11-11 00:00:00 2022-01-10 00:00:00
The join:
sqldf::sqldf("
select df11.*, df22.DOB, df22.EncounterDate, df22.Type, df22.responses
from df11
left join df22 on df11.UserID = df22.UserID
and df22.EncounterDate between df11.Date_m30 and df11.Date_p30") %>%
select(-Date_m30, -Date_p30)
# UserID Full.Name Info EncounterID Date Temp misc DOB EncounterDate Type responses
# 1 1 John Smith yes 13 2021-01-01 19:00:00 100 (null) 1/1/90 2020-12-31 19:00:00 Intro (null)
# 2 2 Jack Peters no 14 2021-01-04 19:00:00 103 no 1/10/90 2021-01-01 19:00:00 Intro no
# 3 3 Bob Brown yes 15 2020-12-31 19:00:00 104 (null) 1/2/90 2020-12-31 19:00:00 Intro yes
# 4 4 Jane Doe yes 16 2021-01-04 19:00:00 103 (null) 2/20/80 2021-01-05 19:00:00 Intro no
# 5 5 Jackie Jane yes 17 2021-05-08 20:00:00 101 (null) 2/2/80 2021-05-06 20:00:00 Care no
# 6 6 Sarah Brown yes 18 2021-05-07 20:00:00 102 (null) 12/2/80 2021-05-07 20:00:00 Out unsat
# 7 7 Chloe Brown no 19 2021-12-11 19:00:00 103 (null)
# 8 1 John Smith yes 13 2021-12-10 19:00:00 105 (null)
QUESTION
I have the following dataframe:
df = pd.DataFrame({"marks": [40, 60, 90, 20, 100, 10, 30, 70 ], "students":
["Jack", "Jack", "Jack", "Jack", "John", "John", "John", "John"]}
)
marks students
0 40 Jack
1 60 Jack
2 90 Jack
3 20 Jack
4 100 John
5 10 John
6 30 John
7 70 John
I am attempting to assign a student's average to his marks below 40 (the average will include the lowest mark).
I am aware of assigning a mark based on the < 40
condition (in this case I assigned the lowest mark of the df to all marks below 40), like so:
df.loc[df["marks"] < 40, "marks"] = df["marks"].min()
But I am confused on how to potentially apply a lambda function on unique student
names. Any help would be appreciated.
ANSWER
Answered 2021-Aug-15 at 13:50You can combine a groupby
and where
:
df['corrected_marks'] = df['marks'].where(df['marks']>=40,
(df.groupby('students')
['marks']
.transform('mean'))
)
output:
marks students corrected_marks
0 40 Jack 40.0
1 60 Jack 60.0
2 90 Jack 90.0
3 20 Jack 52.5
4 100 John 100.0
5 10 John 52.5
6 30 John 52.5
7 70 John 70.0
Community Discussions, Code Snippets contain sources that include Stack Exchange Network
Vulnerabilities
No vulnerabilities reported
Install jack
Support
Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from over 650 million Knowledge Items
Find more librariesExplore Kits - Develop, implement, customize Projects, Custom Functions and Applications with kandi kits
Save this library and start creating your kit
Share this Page