prompt stringlengths 105 4.73k | reference_code stringlengths 11 774 | code_context stringlengths 746 120k | problem_id int64 0 999 | library_problem_id int64 0 290 | library class label 7
classes | test_case_cnt int64 0 5 | perturbation_type class label 4
classes | perturbation_origin_id int64 0 289 |
|---|---|---|---|---|---|---|---|---|
Problem:
In pandas, how do I replace & with '&' from all columns where & could be in any position in a string?
For example, in column Title if there is a value 'Good & bad', how do I replace it with 'Good & bad'?
A:
<code>
import pandas as pd
df = pd.DataFrame({'A': ['Good & bad', 'BB', 'CC', 'DD', '... | def g(df):
return df.replace('&','&', regex=True)
df = g(df.copy())
| import pandas as pd
import numpy as np
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
df = data
return df.replace("&", "&", regex=True)
def define_test_input(test_case_id):
if test_case_id == 1:
df = pd.DataFrame(
{
... | 100 | 100 | 2Pandas | 1 | 1Origin | 100 |
Problem:
In pandas, how do I replace < with '<' from all columns where < could be in any position in a string?
For example, in column Title if there is a value 'Good < bad', how do I replace it with 'Good < bad'?
A:
<code>
import pandas as pd
df = pd.DataFrame({'A': ['Good < bad', 'BB', 'CC', 'DD', 'Good ... | def g(df):
return df.replace('<','<', regex=True)
df = g(df.copy())
| import pandas as pd
import numpy as np
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
df = data
return df.replace("<", "<", regex=True)
def define_test_input(test_case_id):
if test_case_id == 1:
df = pd.DataFrame(
{
... | 101 | 101 | 2Pandas | 1 | 2Semantic | 100 |
Problem:
In pandas, how do I replace & with '&' from all columns where & could be in any position in a string?
For example, in column Title if there is a value 'Good & bad', how do I replace it with 'Good & bad'?
A:
<code>
import pandas as pd
example_df = pd.DataFrame({'A': ['Good & bad', 'BB', 'CC', ... | result = df.replace('&','&', regex=True)
return result
| import pandas as pd
import numpy as np
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
df = data
return df.replace("&", "&", regex=True)
def define_test_input(test_case_id):
if test_case_id == 1:
df = pd.DataFrame(
{
... | 102 | 102 | 2Pandas | 1 | 3Surface | 100 |
Problem:
In pandas, how do I replace &,<,> with '&''<''>' from all columns where & could be in any position in a string?
For example, in column Title if there is a value 'Good & bad', how do I replace it with 'Good & bad'?
A:
<code>
import pandas as pd
df = pd.DataFrame({'A': ['Good & bad', 'BB... | def g(df):
df.replace('&', '&', regex=True, inplace=True)
df.replace('<', '<', regex=True, inplace=True)
df.replace('>', '>', regex=True, inplace=True)
return df
df = g(df.copy())
| import pandas as pd
import numpy as np
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
df = data
df.replace("&", "&", regex=True, inplace=True)
df.replace("<", "<", regex=True, inplace=True)
df.replace(">", ">", regex=True, inplace=True)
... | 103 | 103 | 2Pandas | 1 | 0Difficult-Rewrite | 100 |
Problem:
In pandas, how do I replace & with '&' from all columns where & could be in any position in a string?Then please evaluate this expression.
For example, in column Title if there is a value '1 & 0', how do I replace it with '1 & 0 = 0'?
A:
<code>
import pandas as pd
df = pd.DataFrame({'A': ['1 &AM... | def g(df):
for i in df.index:
for col in list(df):
if type(df.loc[i, col]) == str:
if '&' in df.loc[i, col]:
df.loc[i, col] = df.loc[i, col].replace('&', '&')
df.loc[i, col] = df.loc[i, col]+' = '+str(eval(df.loc[i, col]))
df.re... | import pandas as pd
import numpy as np
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
df = data
for i in df.index:
for col in list(df):
if type(df.loc[i, col]) == str:
if "&" in df.loc[i, col]:
d... | 104 | 104 | 2Pandas | 1 | 0Difficult-Rewrite | 100 |
Problem:
Let's say I have a pandas DataFrame containing names like so:
name_df = pd.DataFrame({'name':['Jack Fine','Kim Q. Danger','Jane Smith', 'Juan de la Cruz']})
name
0 Jack Fine
1 Kim Q. Danger
2 Jane Smith
3 Juan de la Cruz
and I want to split the name column into first_name and last_name IF there i... | def g(df):
df.loc[df['name'].str.split().str.len() == 2, 'last_name'] = df['name'].str.split().str[-1]
df.loc[df['name'].str.split().str.len() == 2, 'name'] = df['name'].str.split().str[0]
df.rename(columns={'name': 'first_name'}, inplace=True)
return df
df = g(df.copy())
| import pandas as pd
import numpy as np
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
df = data
df.loc[df["name"].str.split().str.len() == 2, "last_name"] = (
df["name"].str.split().str[-1]
)
df.loc[df["name"].str.split().str.len() == 2, "name... | 105 | 105 | 2Pandas | 1 | 1Origin | 105 |
Problem:
Let's say I have a pandas DataFrame containing names like so:
name_df = pd.DataFrame({'name':['Jack Fine','Kim Q. Danger','Jane Smith', 'Juan de la Cruz']})
name
0 Jack Fine
1 Kim Q. Danger
2 Jane Smith
3 Juan de la Cruz
and I want to split the name column into 1_name and 2_name IF there is one s... | def g(df):
df.loc[df['name'].str.split().str.len() == 2, '2_name'] = df['name'].str.split().str[-1]
df.loc[df['name'].str.split().str.len() == 2, 'name'] = df['name'].str.split().str[0]
df.rename(columns={'name': '1_name'}, inplace=True)
return df
df = g(df.copy())
| import pandas as pd
import numpy as np
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
df = data
df.loc[df["name"].str.split().str.len() == 2, "2_name"] = (
df["name"].str.split().str[-1]
)
df.loc[df["name"].str.split().str.len() == 2, "name"] ... | 106 | 106 | 2Pandas | 1 | 2Semantic | 105 |
Problem:
Let's say I have a pandas DataFrame containing names like so:
name_df = pd.DataFrame({'name':['Jack Fine','Kim Q. Danger','Jane Smith', 'Juan de la Cruz']})
name
0 Jack Fine
1 Kim Q. Danger
2 Jane 114 514 Smith
3 Zhongli
and I want to split the name column into f... | def g(df):
df.loc[df['name'].str.split().str.len() >= 3, 'middle_name'] = df['name'].str.split().str[1:-1]
for i in range(len(df)):
if len(df.loc[i, 'name'].split()) >= 3:
l = df.loc[i, 'name'].split()[1:-1]
s = l[0]
for j in range(1,len(l)):
s += ' '+... | import pandas as pd
import numpy as np
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
df = data
df.loc[df["name"].str.split().str.len() >= 3, "middle_name"] = (
df["name"].str.split().str[1:-1]
)
for i in range(len(df)):
if len(df.... | 107 | 107 | 2Pandas | 1 | 0Difficult-Rewrite | 105 |
Problem:
Say I have two dataframes:
df1: df2:
+-------------------+----+ +-------------------+-----+
| Timestamp |data| | Timestamp |stuff|
+-------------------+----+ +-------------------+-----+
|2019/04/02 11:00:01| 111| |2019/04/02 11:00:14| 101|
|2019/04/02 11:00... | def g(df1, df2):
return pd.merge_asof(df2, df1, on='Timestamp', direction='forward')
result = g(df1.copy(), df2.copy())
| import pandas as pd
import numpy as np
import copy
import tokenize, io
def generate_test_case(test_case_id):
def generate_ans(data):
data = data
df1, df2 = data
return pd.merge_asof(df2, df1, on="Timestamp", direction="forward")
def define_test_input(test_case_id):
if test_cas... | 108 | 108 | 2Pandas | 2 | 1Origin | 108 |
Problem:
Say I have two dataframes:
df1: df2:
+-------------------+----+ +-------------------+-----+
| Timestamp |data| | Timestamp |stuff|
+-------------------+----+ +-------------------+-----+
|2019/04/02 11:00:01| 111| |2019/04/02 11:00:14| 101|
|2019/04/02 11:00... | def g(df1, df2):
return pd.merge_asof(df1, df2, on='Timestamp', direction='forward')
result = g(df1.copy(), df2.copy())
| import pandas as pd
import numpy as np
import copy
import tokenize, io
def generate_test_case(test_case_id):
def generate_ans(data):
data = data
df1, df2 = data
return pd.merge_asof(df1, df2, on="Timestamp", direction="forward")
def define_test_input(test_case_id):
if test_cas... | 109 | 109 | 2Pandas | 2 | 2Semantic | 108 |
Problem:
I have an example data as:
datetime col1 col2 col3
2021-04-10 01:00:00 25. 50. 50
2021-04-10 02:00:00. 25. 50. 50
2021-04-10 03:00:00. 25. 100. 50
2021-04-10 04:00:00 50. 50. 100
2021-04-10 05:00:00. 100. 100. 100
I want to create a new column cal... | import numpy as np
def g(df):
df['state'] = np.where((df['col2'] <= 50) & (df['col3'] <= 50), df['col1'], df[['col1', 'col2', 'col3']].max(axis=1))
return df
df = g(df.copy())
| import pandas as pd
import numpy as np
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
df = data
df["state"] = np.where(
(df["col2"] <= 50) & (df["col3"] <= 50),
df["col1"],
df[["col1", "col2", "col3"]].max(axis=1),
)
re... | 110 | 110 | 2Pandas | 2 | 1Origin | 110 |
Problem:
I have an example data as:
datetime col1 col2 col3
2021-04-10 01:00:00 25. 50. 50
2021-04-10 02:00:00. 25. 50. 50
2021-04-10 03:00:00. 25. 100. 50
2021-04-10 04:00:00 50. 50. 100
2021-04-10 05:00:00. 100. 100. 100
I want to create a new column cal... | import numpy as np
def g(df):
df['state'] = np.where((df['col2'] > 50) & (df['col3'] > 50), df['col1'], df[['col1', 'col2', 'col3']].sum(axis=1))
return df
df = g(df.copy())
| import pandas as pd
import numpy as np
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
df = data
df["state"] = np.where(
(df["col2"] > 50) & (df["col3"] > 50),
df["col1"],
df[["col1", "col2", "col3"]].sum(axis=1),
)
retu... | 111 | 111 | 2Pandas | 2 | 2Semantic | 110 |
Problem:
I have a pandas dataframe with a column which could have integers, float, string etc. I would like to iterate over all the rows and check if each value is integer and if not, I would like to create a list with error values (values that are not integer)
I have tried isnumeric(), but couldnt iterate over each ro... | def g(df):
return df.loc[~df['Field1'].astype(str).str.isdigit(), 'Field1'].tolist()
df = g(df.copy())
| import pandas as pd
import numpy as np
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
df = data
return df.loc[~df["Field1"].astype(str).str.isdigit(), "Field1"].tolist()
def define_test_input(test_case_id):
if test_case_id == 1:
df = pd.DataFrame... | 112 | 112 | 2Pandas | 2 | 1Origin | 112 |
Problem:
I have a pandas dataframe with a column which could have integers, float, string etc. I would like to iterate over all the rows and check if each value is integer and if not, I would like to create a list with integer values
I have tried isnumeric(), but couldnt iterate over each row and write errors to output... | def g(df):
return df.loc[df['Field1'].astype(str).str.isdigit(), 'Field1'].tolist()
df = g(df.copy())
| import pandas as pd
import numpy as np
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
df = data
return df.loc[df["Field1"].astype(str).str.isdigit(), "Field1"].tolist()
def define_test_input(test_case_id):
if test_case_id == 1:
df = pd.DataFrame(... | 113 | 113 | 2Pandas | 2 | 2Semantic | 112 |
Problem:
I have a pandas dataframe with a column which could have integers, float, string etc. I would like to iterate over all the rows and check if each value is integer and if not, I would like to create a list with error values (values that are not integer)
I have tried isnumeric(), but couldnt iterate over each ro... | result = df.loc[~df['Field1'].astype(str).str.isdigit(), 'Field1'].tolist()
return result
| import pandas as pd
import numpy as np
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
df = data
return df.loc[~df["Field1"].astype(str).str.isdigit(), "Field1"].tolist()
def define_test_input(test_case_id):
if test_case_id == 1:
df = pd.DataFrame... | 114 | 114 | 2Pandas | 2 | 3Surface | 112 |
Problem:
I have my data in a pandas DataFrame, and it looks like the following:
cat val1 val2 val3 val4
A 7 10 0 19
B 10 2 1 14
C 5 15 6 16
I'd like to compute the percentage of the category (cat) that each value has.
For example, for category A, val1 is 7 an... | def g(df):
df = df.set_index('cat')
res = df.div(df.sum(axis=1), axis=0)
return res.reset_index()
df = g(df.copy())
| import pandas as pd
import numpy as np
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
df = data
df = df.set_index("cat")
res = df.div(df.sum(axis=1), axis=0)
return res.reset_index()
def define_test_input(test_case_id):
if test_case_id == 1:
... | 115 | 115 | 2Pandas | 2 | 1Origin | 115 |
Problem:
I have my data in a pandas DataFrame, and it looks like the following:
cat val1 val2 val3 val4
A 7 10 0 19
B 10 2 1 14
C 5 15 6 16
I'd like to compute the percentage of the value that each category(cat) has.
For example, for val1, A is 7 and the colu... | def g(df):
df = df.set_index('cat')
res = df.div(df.sum(axis=0), axis=1)
return res.reset_index()
df = g(df.copy())
| import pandas as pd
import numpy as np
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
df = data
df = df.set_index("cat")
res = df.div(df.sum(axis=0), axis=1)
return res.reset_index()
def define_test_input(test_case_id):
if test_case_id == 1:
... | 116 | 116 | 2Pandas | 2 | 2Semantic | 115 |
Problem:
I am trying to extract rows from a Pandas dataframe using a list of row names, but it can't be done. Here is an example
# df
alleles chrom pos strand assembly# center protLSID assayLSID
rs#
TP3 A/C 0 3 + NaN NaN NaN NaN
TP7 A/T 0 7 + ... | def g(df, test):
return df.loc[test]
result = g(df, test)
| import pandas as pd
import numpy as np
import os
import io
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
data = data
df, test = data
return df.loc[test]
def define_test_input(test_case_id):
if test_case_id == 1:
data = io.StringIO(
... | 117 | 117 | 2Pandas | 1 | 1Origin | 117 |
Problem:
I am trying to extract rows from a Pandas dataframe using a list of row names, but it can't be done. Here is an example
# df
alias chrome poston
rs#
TP3 A/C 0 3
TP7 A/T 0 7
TP12 T/A 0 12
TP15 C/A 0 15
TP18 C/T 0 18
rows = ['TP3', 'T... | def g(df, test):
return df.loc[test]
result = g(df, test)
| import pandas as pd
import numpy as np
import io
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
data = data
df, test = data
return df.loc[test]
def define_test_input(test_case_id):
if test_case_id == 1:
data = io.StringIO(
... | 118 | 118 | 2Pandas | 1 | 3Surface | 117 |
Problem:
I am trying to delete rows from a Pandas dataframe using a list of row names, but it can't be done. Here is an example
# df
alleles chrom pos strand assembly# center protLSID assayLSID
rs#
TP3 A/C 0 3 + NaN NaN NaN NaN
TP7 A/T 0 7 + ... | result = df.drop(test, inplace = False)
| import pandas as pd
import numpy as np
import io
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
data = data
df, test = data
return df.drop(test, inplace=False)
def define_test_input(test_case_id):
if test_case_id == 1:
data = io.StringIO(... | 119 | 119 | 2Pandas | 1 | 2Semantic | 117 |
Problem:
I am trying to extract rows from a Pandas dataframe using a list of row names according to the order of the list, but it can't be done. Note that the list might contain duplicate row names, and I just want the row occurs once. Here is an example
# df
alleles chrom pos strand assembly# center protLSI... | result = df.loc[df.index.isin(test)]
return result
| import pandas as pd
import numpy as np
import io
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
data = data
df, test = data
return df.loc[df.index.isin(test)]
def define_test_input(test_case_id):
if test_case_id == 1:
data = io.StringIO(
... | 120 | 120 | 2Pandas | 1 | 0Difficult-Rewrite | 117 |
Problem:
I have a set of objects and their positions over time. I would like to get the distance between each car and their nearest neighbour, and calculate an average of this for each time point. An example dataframe is as follows:
time = [0, 0, 0, 1, 1, 2, 2]
x = [216, 218, 217, 280, 290, 130, 132]
y = [13, 12, 12... | import numpy as np
def g(df):
time = df.time.tolist()
car = df.car.tolist()
nearest_neighbour = []
euclidean_distance = []
for i in range(len(df)):
n = 0
d = np.inf
for j in range(len(df)):
if df.loc[i, 'time'] == df.loc[j, 'time'] and df.loc[i, 'car'] != df.loc[j... | import pandas as pd
import numpy as np
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
df = data
time = df.time.tolist()
car = df.car.tolist()
nearest_neighbour = []
euclidean_distance = []
for i in range(len(df)):
n = 0
... | 121 | 121 | 2Pandas | 2 | 1Origin | 121 |
Problem:
I have a set of objects and their positions over time. I would like to get the distance between each car and their farmost neighbour, and calculate an average of this for each time point. An example dataframe is as follows:
time = [0, 0, 0, 1, 1, 2, 2]
x = [216, 218, 217, 280, 290, 130, 132]
y = [13, 12, 12... | import numpy as np
def g(df):
time = df.time.tolist()
car = df.car.tolist()
farmost_neighbour = []
euclidean_distance = []
for i in range(len(df)):
n = 0
d = 0
for j in range(len(df)):
if df.loc[i, 'time'] == df.loc[j, 'time'] and df.loc[i, 'car'] != df.loc[j, 'ca... | import pandas as pd
import numpy as np
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
df = data
time = df.time.tolist()
car = df.car.tolist()
farmost_neighbour = []
euclidean_distance = []
for i in range(len(df)):
n = 0
... | 122 | 122 | 2Pandas | 2 | 2Semantic | 121 |
Problem:
My sample df has four columns with NaN values. The goal is to concatenate all the rows while excluding the NaN values.
import pandas as pd
import numpy as np
df = pd.DataFrame({'keywords_0':["a", np.nan, "c"],
'keywords_1':["d", "e", np.nan],
'keywords_2':[np.nan, np.nan, "b"]... | import numpy as np
def g(df):
df["keywords_all"] = df.apply(lambda x: ','.join(x.dropna()), axis=1)
return df
df = g(df.copy())
| import pandas as pd
import numpy as np
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
df = data
df["keywords_all"] = df.apply(lambda x: ",".join(x.dropna()), axis=1)
return df
def define_test_input(test_case_id):
if test_case_id == 1:
df ... | 123 | 123 | 2Pandas | 2 | 1Origin | 123 |
Problem:
My sample df has four columns with NaN values. The goal is to concatenate all the rows while excluding the NaN values.
import pandas as pd
import numpy as np
df = pd.DataFrame({'keywords_0':["a", np.nan, "c"],
'keywords_1':["d", "e", np.nan],
'keywords_2':[np.nan, np.nan, "b"]... | import numpy as np
def g(df):
df["keywords_all"] = df.apply(lambda x: '-'.join(x.dropna()), axis=1)
return df
df = g(df.copy())
| import pandas as pd
import numpy as np
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
df = data
df["keywords_all"] = df.apply(lambda x: "-".join(x.dropna()), axis=1)
return df
def define_test_input(test_case_id):
if test_case_id == 1:
df ... | 124 | 124 | 2Pandas | 2 | 2Semantic | 123 |
Problem:
My sample df has four columns with NaN values. The goal is to concatenate all the keywords rows while excluding the NaN values.
import pandas as pd
import numpy as np
df = pd.DataFrame({'users': ['Hu Tao', 'Zhongli', 'Xingqiu'],
'keywords_0': ["a", np.nan, "c"],
'keywords_... | import numpy as np
def g(df):
df["keywords_all"] = df.filter(like='keyword').apply(lambda x: '-'.join(x.dropna()), axis=1)
return df
df = g(df.copy())
| import pandas as pd
import numpy as np
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
df = data
df["keywords_all"] = df.filter(like="keyword").apply(
lambda x: "-".join(x.dropna()), axis=1
)
return df
def define_test_input(test_case_id):
... | 125 | 125 | 2Pandas | 2 | 0Difficult-Rewrite | 123 |
Problem:
My sample df has four columns with NaN values. The goal is to concatenate all the kewwords rows from end to front while excluding the NaN values.
import pandas as pd
import numpy as np
df = pd.DataFrame({'users': ['Hu Tao', 'Zhongli', 'Xingqiu'],
'keywords_0': ["a", np.nan, "c"],
... | import numpy as np
def g(df):
df["keywords_all"] = df.filter(like='keyword').apply(lambda x: '-'.join(x.dropna()), axis=1)
for i in range(len(df)):
df.loc[i, "keywords_all"] = df.loc[i, "keywords_all"][::-1]
return df
df = g(df.copy())
| import pandas as pd
import numpy as np
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
df = data
df["keywords_all"] = df.filter(like="keyword").apply(
lambda x: "-".join(x.dropna()), axis=1
)
for i in range(len(df)):
df.loc[i, "keyw... | 126 | 126 | 2Pandas | 2 | 0Difficult-Rewrite | 123 |
Problem:
I have a pandas Dataframe like below:
UserId ProductId Quantity
1 1 6
1 4 1
1 7 3
2 4 2
3 2 7
3 1 2
Now, I want to randomly select the 20% of rows of this DataFrame, using df.sample(n), set... | def g(df):
l = int(0.2 * len(df))
dfupdate = df.sample(l, random_state=0)
dfupdate.Quantity = 0
df.update(dfupdate)
return df
df = g(df.copy())
| import pandas as pd
import numpy as np
import copy
import tokenize, io
def generate_test_case(test_case_id):
def generate_ans(data):
df = data
l = int(0.2 * len(df))
dfupdate = df.sample(l, random_state=0)
dfupdate.Quantity = 0
df.update(dfupdate)
return df
def... | 127 | 127 | 2Pandas | 2 | 1Origin | 127 |
Problem:
I have a pandas Dataframe like below:
UserId ProductId Quantity
1 1 6
1 4 1
1 7 3
2 4 2
3 2 7
3 1 2
Now, I want to randomly select the 20% of rows of this DataFrame, using df.sample(n), set... | def g(df):
l = int(0.2 * len(df))
dfupdate = df.sample(l, random_state=0)
dfupdate.ProductId = 0
df.update(dfupdate)
return df
df = g(df.copy())
| import pandas as pd
import numpy as np
import copy
import tokenize, io
def generate_test_case(test_case_id):
def generate_ans(data):
df = data
l = int(0.2 * len(df))
dfupdate = df.sample(l, random_state=0)
dfupdate.ProductId = 0
df.update(dfupdate)
return df
de... | 128 | 128 | 2Pandas | 2 | 2Semantic | 127 |
Problem:
I have a pandas Dataframe like below:
UserId ProductId Quantity
0 1 1 6
1 1 4 1
2 1 7 3
3 1 4 2
4 1 2 7
5 2 1 2
6 2 1 6
7 2 ... | def g(df):
for i in range(len(df)):
tot = 0
if i != 0:
if df.loc[i, 'UserId'] == df.loc[i-1, 'UserId']:
continue
for j in range(len(df)):
if df.loc[i, 'UserId'] == df.loc[j, 'UserId']:
tot += 1
l = int(0.2*tot)
dfupdate ... | import pandas as pd
import numpy as np
import copy
import tokenize, io
def generate_test_case(test_case_id):
def generate_ans(data):
df = data
for i in range(len(df)):
tot = 0
if i != 0:
if df.loc[i, "UserId"] == df.loc[i - 1, "UserId"]:
... | 129 | 129 | 2Pandas | 2 | 0Difficult-Rewrite | 127 |
Problem:
I am trying to find duplicates rows in a pandas dataframe.
df=pd.DataFrame(data=[[1,2],[3,4],[1,2],[1,4],[1,2]],columns=['col1','col2'])
df
Out[15]:
col1 col2
0 1 2
1 3 4
2 1 2
3 1 4
4 1 2
duplicate_bool = df.duplicated(subset=['col1','col2'], keep='first')
duplicat... | def g(df):
df['index_original'] = df.groupby(['col1', 'col2']).col1.transform('idxmin')
return df[df.duplicated(subset=['col1', 'col2'], keep='first')]
result = g(df.copy())
| import pandas as pd
import numpy as np
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
df = data
df["index_original"] = df.groupby(["col1", "col2"]).col1.transform("idxmin")
return df[df.duplicated(subset=["col1", "col2"], keep="first")]
def define_test_input... | 130 | 130 | 2Pandas | 2 | 1Origin | 130 |
Problem:
I am trying to find duplicates rows in a pandas dataframe.
df=pd.DataFrame(data=[[1,2],[3,4],[1,2],[1,4],[1,2]],columns=['col1','col2'])
df
Out[15]:
col1 col2
0 1 2
1 3 4
2 1 2
3 1 4
4 1 2
duplicate_bool = df.duplicated(subset=['col1','col2'], keep='last')
duplicate... | def g(df):
df['index_original'] = df.groupby(['col1', 'col2']).col1.transform('idxmax')
for i in range(len(df)):
i = len(df) - 1 - i
origin = df.loc[i, 'index_original']
if i <= origin:
continue
if origin == df.loc[origin, 'index_original']:
df.loc[origin,... | import pandas as pd
import numpy as np
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
df = data
df["index_original"] = df.groupby(["col1", "col2"]).col1.transform("idxmax")
for i in range(len(df)):
i = len(df) - 1 - i
origin = df.loc[i, "i... | 131 | 131 | 2Pandas | 2 | 2Semantic | 130 |
Problem:
I am trying to find duplicates rows in a pandas dataframe.
df=pd.DataFrame(data=[[1,2],[3,4],[1,2],[1,4],[1,2]],columns=['col1','col2'])
df
Out[15]:
col1 col2
0 1 2
1 3 4
2 1 2
3 1 4
4 1 2
duplicate_bool = df.duplicated(subset=['col1','col2'], keep='first')
duplicat... | df['index_original'] = df.groupby(['col1', 'col2']).col1.transform('idxmin')
result = df[df.duplicated(subset=['col1', 'col2'], keep='first')]
return result
| import pandas as pd
import numpy as np
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
df = data
df["index_original"] = df.groupby(["col1", "col2"]).col1.transform("idxmin")
return df[df.duplicated(subset=["col1", "col2"], keep="first")]
def define_test_input... | 132 | 132 | 2Pandas | 2 | 3Surface | 130 |
Problem:
I am trying to find col duplicates rows in a pandas dataframe.
df=pd.DataFrame(data=[[1,1,2,5],[1,3,4,1],[4,1,2,5],[5,1,4,9],[1,1,2,5]],columns=['val', 'col1','col2','3col'])
df
Out[15]:
val col1 col2 3col
0 1 1 2 5
1 1 3 4 1
2 4 1 2 5
3 5 1 4 ... | def g(df):
cols = list(df.filter(like='col'))
df['index_original'] = df.groupby(cols)[cols[0]].transform('idxmin')
return df[df.duplicated(subset=cols, keep='first')]
result = g(df.copy())
| import pandas as pd
import numpy as np
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
df = data
cols = list(df.filter(like="col"))
df["index_original"] = df.groupby(cols)[cols[0]].transform("idxmin")
return df[df.duplicated(subset=cols, keep="first")]
... | 133 | 133 | 2Pandas | 2 | 0Difficult-Rewrite | 130 |
Problem:
I am trying to find duplicates col rows in a pandas dataframe.
df=pd.DataFrame(data=[[1,1,2,5],[1,3,4,1],[4,1,2,5],[5,1,4,9],[1,1,2,5]],columns=['val', 'col1','col2','3col'])
df
Out[15]:
val col1 col2 3col
0 1 1 2 5
1 1 3 4 1
2 4 1 2 5
3 5 1 4 ... | def g(df):
cols = list(df.filter(like='col'))
df['index_original'] = df.groupby(cols)[cols[0]].transform('idxmax')
for i in range(len(df)):
i = len(df) - 1 - i
origin = df.loc[i, 'index_original']
if i <= origin:
continue
if origin == df.loc[origin, 'index_origina... | import pandas as pd
import numpy as np
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
df = data
cols = list(df.filter(like="col"))
df["index_original"] = df.groupby(cols)[cols[0]].transform("idxmax")
for i in range(len(df)):
i = len(df) - 1 - ... | 134 | 134 | 2Pandas | 2 | 0Difficult-Rewrite | 130 |
Problem:
How do I find all rows in a pandas DataFrame which have the max value for count column, after grouping by ['Sp','Mt'] columns?
Example 1: the following DataFrame, which I group by ['Sp','Mt']:
Sp Mt Value count
0 MM1 S1 a **3**
1 MM1 S1 n 2
2 MM1 S3 cb **5**
3 MM2 S3 mk ... | def g(df):
return df[df.groupby(['Sp', 'Mt'])['count'].transform(max) == df['count']]
result = g(df.copy())
| import pandas as pd
import numpy as np
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
df = data
return df[df.groupby(["Sp", "Mt"])["count"].transform(max) == df["count"]]
def define_test_input(test_case_id):
if test_case_id == 1:
df = pd.DataFram... | 135 | 135 | 2Pandas | 1 | 1Origin | 135 |
Problem:
How do I find all rows in a pandas DataFrame which have the max value for count column, after grouping by ['Sp','Mt'] columns?
Example 1: the following DataFrame, which I group by ['Sp','Mt']:
Sp Mt Value count
0 MM1 S1 a **3**
1 MM1 S1 n 2
2 MM1 S3 cb **5**
3 MM2 S3 mk ... | def g(df):
return df[df.groupby(['Sp', 'Mt'])['count'].transform(max) == df['count']]
result = g(df.copy())
| import pandas as pd
import numpy as np
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
df = data
return df[df.groupby(["Sp", "Mt"])["count"].transform(max) == df["count"]]
def define_test_input(test_case_id):
if test_case_id == 1:
df = pd.DataFram... | 136 | 136 | 2Pandas | 2 | 3Surface | 135 |
Problem:
How do I find all rows in a pandas DataFrame which have the min value for count column, after grouping by ['Sp','Mt'] columns?
Example 1: the following DataFrame, which I group by ['Sp','Mt']:
Sp Mt Value count
0 MM1 S1 a **3**
1 MM1 S1 n 2
2 MM1 S3 cb **5**
3 MM2 S3 mk ... | def g(df):
return df[df.groupby(['Sp', 'Mt'])['count'].transform(min) == df['count']]
result = g(df.copy())
| import pandas as pd
import numpy as np
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
df = data
return df[df.groupby(["Sp", "Mt"])["count"].transform(min) == df["count"]]
def define_test_input(test_case_id):
if test_case_id == 1:
df = pd.DataFram... | 137 | 137 | 2Pandas | 2 | 2Semantic | 135 |
Problem:
How do I find all rows in a pandas DataFrame which have the max value for count column, after grouping by ['Sp','Value'] columns?
Example 1: the following DataFrame, which I group by ['Sp','Value']:
Sp Value Mt count
0 MM1 S1 a 3
1 MM1 S1 n 2
2 MM1 S3 cb 5
3 MM2 ... | def g(df):
return df[df.groupby(['Sp', 'Value'])['count'].transform(max) == df['count']]
result = g(df.copy())
| import pandas as pd
import numpy as np
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
df = data
return df[df.groupby(["Sp", "Value"])["count"].transform(max) == df["count"]]
def define_test_input(test_case_id):
if test_case_id == 1:
df = pd.DataF... | 138 | 138 | 2Pandas | 2 | 0Difficult-Rewrite | 135 |
Problem:
I am performing a query on a DataFrame:
Index Category
1 Foo
2 Bar
3 Cho
4 Foo
I would like to return the rows where the category is "Foo" or "Bar".
When I use the code:
df.query("Catergory==['Foo','Bar']")
This works fine and returns:
Index Category
1 Foo
2 Bar
4 Foo
However ... | def g(df, filter_list):
return df.query("Category == @filter_list")
result = g(df.copy(), filter_list)
| import pandas as pd
import numpy as np
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
data = data
df, filter_list = data
return df.query("Category == @filter_list")
def define_test_input(test_case_id):
if test_case_id == 1:
df = pd.DataFr... | 139 | 139 | 2Pandas | 2 | 1Origin | 139 |
Problem:
I am performing a query on a DataFrame:
Index Category
1 Foo
2 Bar
3 Cho
4 Foo
I would like to return the rows where the category is not "Foo" or "Bar".
When I use the code:
df.query("Catergory!=['Foo','Bar']")
This works fine and returns:
Index Category
3 Cho
However in future I will... | def g(df, filter_list):
return df.query("Category != @filter_list")
result = g(df.copy(), filter_list)
| import pandas as pd
import numpy as np
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
data = data
df, filter_list = data
return df.query("Category != @filter_list")
def define_test_input(test_case_id):
if test_case_id == 1:
df = pd.DataFr... | 140 | 140 | 2Pandas | 2 | 2Semantic | 139 |
Problem:
I have a Pandas DataFrame that looks something like:
df = pd.DataFrame({'col1': {0: 'a', 1: 'b', 2: 'c'},
'col2': {0: 1, 1: 3, 2: 5},
'col3': {0: 2, 1: 4, 2: 6},
'col4': {0: 3, 1: 6, 2: 2},
'col5': {0: 7, 1: 2, 2: 3},
... | def g(df):
return pd.melt(df)
result = g(df.copy())
| import pandas as pd
import numpy as np
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
df = data
return pd.melt(df)
def define_test_input(test_case_id):
if test_case_id == 1:
df = pd.DataFrame(
{
"col1": {0: "a"... | 141 | 141 | 2Pandas | 2 | 1Origin | 141 |
Problem:
I have a Pandas DataFrame that looks something like:
df = pd.DataFrame({'col1': {0: 'a', 1: 'b', 2: 'c'},
'col2': {0: 1, 1: 3, 2: 5},
'col3': {0: 2, 1: 4, 2: 6},
'col4': {0: 3, 1: 6, 2: 2},
'col5': {0: 7, 1: 2, 2: 3},
... | def g(df):
result = pd.melt(df, value_vars=df.columns.tolist())
cols = result.columns[:-1]
for idx in result.index:
t = result.loc[idx, cols]
for i in range(len(cols)):
result.loc[idx, cols[i]] = t[cols[-i-1]]
return result
result = g(df.copy())
| import pandas as pd
import numpy as np
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
df = data
result = pd.melt(df, value_vars=df.columns.tolist())
cols = result.columns[:-1]
for idx in result.index:
t = result.loc[idx, cols]
for ... | 142 | 142 | 2Pandas | 2 | 2Semantic | 141 |
Problem:
I have
df = pd.DataFrame.from_dict({'id': ['A', 'B', 'A', 'C', 'D', 'B', 'C'], 'val': [1,2,-3,1,5,6,-2], 'stuff':['12','23232','13','1234','3235','3236','732323']})
id stuff val
0 A 12 1
1 B 23232 2
2 A 13 -3
3 C 1234 1
4 D 3235 5
5 B 3236 6
6 C 732323 -2
... | def g(df):
df['cumsum'] = df.groupby('id')['val'].transform(pd.Series.cumsum)
return df
df = g(df.copy())
| import pandas as pd
import numpy as np
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
df = data
df["cumsum"] = df.groupby("id")["val"].transform(pd.Series.cumsum)
return df
def define_test_input(test_case_id):
if test_case_id == 1:
df = p... | 143 | 143 | 2Pandas | 3 | 1Origin | 143 |
Problem:
I have a dataframe containing 2 columns: id and val. I want to get a running sum of val for each id:
For example:
df = pd.DataFrame.from_dict({'id': ['A', 'B', 'A', 'C', 'D', 'B', 'C'], 'val': [1,2,-3,1,5,6,-2], 'stuff':['12','23232','13','1234','3235','3236','732323']})
id stuff val
0 A 12 1
1... | def g(df):
df['cumsum'] = df.groupby('id')['val'].transform(pd.Series.cumsum)
return df
df = g(df.copy())
| import pandas as pd
import numpy as np
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
df = data
df["cumsum"] = df.groupby("id")["val"].transform(pd.Series.cumsum)
return df
def define_test_input(test_case_id):
if test_case_id == 1:
df = p... | 144 | 144 | 2Pandas | 3 | 3Surface | 143 |
Problem:
I have
df = pd.DataFrame.from_dict({'id': ['A', 'B', 'A', 'B'], 'val': [1,2,-3,6], 'stuff':['12','23232','13','3236']})
id stuff val
0 A 12 1
1 B 23232 2
2 A 13 -3
3 B 3236 6
I'd like to get a running sum of val for each id, so the desired output looks like this:
id st... | def g(df):
df['cumsum'] = df.groupby('id')['val'].transform(pd.Series.cumsum)
return df
df = g(df.copy())
| import pandas as pd
import numpy as np
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
df = data
df["cumsum"] = df.groupby("id")["val"].transform(pd.Series.cumsum)
return df
def define_test_input(test_case_id):
if test_case_id == 1:
df = p... | 145 | 145 | 2Pandas | 3 | 3Surface | 143 |
Problem:
I have
df = pd.DataFrame.from_dict({'id': ['A', 'B', 'A', 'C', 'D', 'B', 'C'], 'val': [1,2,-3,1,5,6,-2], 'stuff':['12','23232','13','1234','3235','3236','732323']})
id stuff val
0 A 12 1
1 B 23232 2
2 A 13 -3
3 C 1234 1
4 D 3235 5
5 B 3236 6
6 C 732323 -2
... | def g(df):
df['cummax'] = df.groupby('id')['val'].transform(pd.Series.cummax)
return df
df = g(df.copy())
| import pandas as pd
import numpy as np
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
df = data
df["cummax"] = df.groupby("id")["val"].transform(pd.Series.cummax)
return df
def define_test_input(test_case_id):
if test_case_id == 1:
df = p... | 146 | 146 | 2Pandas | 3 | 2Semantic | 143 |
Problem:
I have
df = pd.DataFrame.from_dict({'id': ['A', 'B', 'A', 'C', 'D', 'B', 'C'], 'val': [1,2,-3,1,5,6,-2], 'stuff':['12','23232','13','1234','3235','3236','732323']})
id stuff val
0 A 12 1
1 B 23232 2
2 A 13 -3
3 C 1234 1
4 D 3235 5
5 B 3236 6
6 C 732323 -2
... | def g(df):
df['cumsum'] = df.groupby('id')['val'].transform(pd.Series.cumsum)
df['cumsum'] = df['cumsum'].where(df['cumsum'] > 0, 0)
return df
df = g(df.copy())
| import pandas as pd
import numpy as np
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
df = data
df["cumsum"] = df.groupby("id")["val"].transform(pd.Series.cumsum)
df["cumsum"] = df["cumsum"].where(df["cumsum"] > 0, 0)
return df
def define_test_input(... | 147 | 147 | 2Pandas | 3 | 0Difficult-Rewrite | 143 |
Problem:
Example
import pandas as pd
import numpy as np
d = {'l': ['left', 'right', 'left', 'right', 'left', 'right'],
'r': ['right', 'left', 'right', 'left', 'right', 'left'],
'v': [-1, 1, -1, 1, -1, np.nan]}
df = pd.DataFrame(d)
Problem
When a grouped dataframe contains a value of np.NaN I want the group... | def g(df):
return df.groupby('l')['v'].apply(pd.Series.sum,skipna=False)
result = g(df.copy())
| import pandas as pd
import numpy as np
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
df = data
return df.groupby("l")["v"].apply(pd.Series.sum, skipna=False)
def define_test_input(test_case_id):
if test_case_id == 1:
d = {
"l": [... | 148 | 148 | 2Pandas | 2 | 1Origin | 148 |
Problem:
Example
import pandas as pd
import numpy as np
d = {'l': ['left', 'right', 'left', 'right', 'left', 'right'],
'r': ['right', 'left', 'right', 'left', 'right', 'left'],
'v': [-1, 1, -1, 1, -1, np.nan]}
df = pd.DataFrame(d)
Problem
When a grouped dataframe contains a value of np.NaN I want the group... | def g(df):
return df.groupby('r')['v'].apply(pd.Series.sum,skipna=False)
result = g(df.copy())
| import pandas as pd
import numpy as np
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
df = data
return df.groupby("r")["v"].apply(pd.Series.sum, skipna=False)
def define_test_input(test_case_id):
if test_case_id == 1:
d = {
"l": [... | 149 | 149 | 2Pandas | 2 | 2Semantic | 148 |
Problem:
Example
import pandas as pd
import numpy as np
d = {'l': ['left', 'right', 'left', 'right', 'left', 'right'],
'r': ['right', 'left', 'right', 'left', 'right', 'left'],
'v': [-1, 1, -1, 1, -1, np.nan]}
df = pd.DataFrame(d)
Problem
When a grouped dataframe contains a value of np.NaN I want the group... | def g(df):
return df.groupby('l')['v'].apply(pd.Series.sum,skipna=False).reset_index()
result = g(df.copy())
| import pandas as pd
import numpy as np
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
df = data
return df.groupby("l")["v"].apply(pd.Series.sum, skipna=False).reset_index()
def define_test_input(test_case_id):
if test_case_id == 1:
d = {
... | 150 | 150 | 2Pandas | 2 | 0Difficult-Rewrite | 148 |
Problem:
Let's say I have 5 columns.
pd.DataFrame({
'Column1': [1, 2, 3, 4, 5, 6, 7, 8, 9],
'Column2': [4, 3, 6, 8, 3, 4, 1, 4, 3],
'Column3': [7, 3, 3, 1, 2, 2, 3, 2, 7],
'Column4': [9, 8, 7, 6, 5, 4, 3, 2, 1],
'Column5': [1, 1, 1, 1, 1, 1, 1, 1, 1]})
Is there a function to know the type of relationship each par of ... | def get_relation(df, col1, col2):
first_max = df[[col1, col2]].groupby(col1).count().max()[0]
second_max = df[[col1, col2]].groupby(col2).count().max()[0]
if first_max==1:
if second_max==1:
return 'one-to-one'
else:
return 'one-to-many'
else:
if second_max... | import pandas as pd
import numpy as np
from itertools import product
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
df = data
def get_relation(df, col1, col2):
first_max = df[[col1, col2]].groupby(col1).count().max()[0]
second_max = df[[col1, col... | 151 | 151 | 2Pandas | 2 | 1Origin | 151 |
Problem:
Let's say I have 5 columns.
pd.DataFrame({
'Column1': [1, 2, 3, 4, 5, 6, 7, 8, 9],
'Column2': [4, 3, 6, 8, 3, 4, 1, 4, 3],
'Column3': [7, 3, 3, 1, 2, 2, 3, 2, 7],
'Column4': [9, 8, 7, 6, 5, 4, 3, 2, 1],
'Column5': [1, 1, 1, 1, 1, 1, 1, 1, 1]})
Is there a function to know the type of relationship each par of ... | def get_relation(df, col1, col2):
first_max = df[[col1, col2]].groupby(col1).count().max()[0]
second_max = df[[col1, col2]].groupby(col2).count().max()[0]
if first_max==1:
if second_max==1:
return 'one-2-one'
else:
return 'one-2-many'
else:
if second_max==... | import pandas as pd
import numpy as np
from itertools import product
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
df = data
def get_relation(df, col1, col2):
first_max = df[[col1, col2]].groupby(col1).count().max()[0]
second_max = df[[col1, col... | 152 | 152 | 2Pandas | 2 | 2Semantic | 151 |
Problem:
Let's say I have 5 columns.
pd.DataFrame({
'Column1': [1, 2, 3, 4, 5, 6, 7, 8, 9],
'Column2': [4, 3, 6, 8, 3, 4, 1, 4, 3],
'Column3': [7, 3, 3, 1, 2, 2, 3, 2, 7],
'Column4': [9, 8, 7, 6, 5, 4, 3, 2, 1],
'Column5': [1, 1, 1, 1, 1, 1, 1, 1, 1]})
Is there a function to know the type of relationship each par of ... | def get_relation(df, col1, col2):
first_max = df[[col1, col2]].groupby(col1).count().max()[0]
second_max = df[[col1, col2]].groupby(col2).count().max()[0]
if first_max==1:
if second_max==1:
return 'one-to-one'
else:
return 'one-to-many'
else:
if second_max... | import pandas as pd
import numpy as np
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
df = data
def get_relation(df, col1, col2):
first_max = df[[col1, col2]].groupby(col1).count().max()[0]
second_max = df[[col1, col2]].groupby(col2).count().max(... | 153 | 153 | 2Pandas | 2 | 0Difficult-Rewrite | 151 |
Problem:
Let's say I have 5 columns.
pd.DataFrame({
'Column1': [1, 2, 3, 4, 5, 6, 7, 8, 9],
'Column2': [4, 3, 6, 8, 3, 4, 1, 4, 3],
'Column3': [7, 3, 3, 1, 2, 2, 3, 2, 7],
'Column4': [9, 8, 7, 6, 5, 4, 3, 2, 1],
'Column5': [1, 1, 1, 1, 1, 1, 1, 1, 1]})
Is there a function to know the type of relationship each par of ... | def get_relation(df, col1, col2):
first_max = df[[col1, col2]].groupby(col1).count().max()[0]
second_max = df[[col1, col2]].groupby(col2).count().max()[0]
if first_max==1:
if second_max==1:
return 'one-2-one'
else:
return 'one-2-many'
else:
if second_max==... | import pandas as pd
import numpy as np
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
df = data
def get_relation(df, col1, col2):
first_max = df[[col1, col2]].groupby(col1).count().max()[0]
second_max = df[[col1, col2]].groupby(col2).count().max(... | 154 | 154 | 2Pandas | 2 | 0Difficult-Rewrite | 151 |
Problem:
I have many duplicate records - some of them have a bank account. I want to keep the records with a bank account.
Basically something like:
if there are two Tommy Joes:
keep the one with a bank account
I have tried to dedupe with the code below, but it is keeping the dupe with no bank account.
df = pd... | def g(df):
uniq_indx = (df.sort_values(by="bank", na_position='last').dropna(subset=['firstname', 'lastname', 'email'])
.applymap(lambda s: s.lower() if type(s) == str else s)
.applymap(lambda x: x.replace(" ", "") if type(x) == str else x)
.drop_duplicates(subset=['firstname'... | import pandas as pd
import numpy as np
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
df = data
uniq_indx = (
df.sort_values(by="bank", na_position="last")
.dropna(subset=["firstname", "lastname", "email"])
.applymap(lambda s: s.lower(... | 155 | 155 | 2Pandas | 1 | 1Origin | 155 |
Problem:
I've read several posts about how to convert Pandas columns to float using pd.to_numeric as well as applymap(locale.atof).
I'm running into problems where neither works.
Note the original Dataframe which is dtype: Object
df.append(df_income_master[", Net"])
Out[76]:
Date
2016-09-30 24.73
2016-06-... | def g(s):
return pd.to_numeric(s.str.replace(',',''), errors='coerce')
result = g(s.copy())
| import pandas as pd
import numpy as np
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
s = data
return pd.to_numeric(s.str.replace(",", ""), errors="coerce")
def define_test_input(test_case_id):
if test_case_id == 1:
s = pd.Series(
... | 156 | 156 | 2Pandas | 2 | 1Origin | 156 |
Problem:
Survived SibSp Parch
0 0 1 0
1 1 1 0
2 1 0 0
3 1 1 0
4 0 0 1
Given the above dataframe, is there an elegant way to groupby with a condition?
I want to split the data into two groups based on the following condition... | import numpy as np
def g(df):
family = np.where((df['SibSp'] + df['Parch']) >= 1 , 'Has Family', 'No Family')
return df.groupby(family)['Survived'].mean()
result = g(df.copy())
| import pandas as pd
import numpy as np
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
df = data
family = np.where((df["SibSp"] + df["Parch"]) >= 1, "Has Family", "No Family")
return df.groupby(family)["Survived"].mean()
def define_test_input(test_case_id):
... | 157 | 157 | 2Pandas | 2 | 1Origin | 157 |
Problem:
Survived SibSp Parch
0 0 1 0
1 1 1 0
2 1 0 0
3 1 1 0
4 0 0 1
Given the above dataframe, is there an elegant way to groupby with a condition?
I want to split the data into two groups based on the following condition... | import numpy as np
def g(df):
family = np.where((df['Survived'] + df['Parch']) >= 1 , 'Has Family', 'No Family')
return df.groupby(family)['SibSp'].mean()
result = g(df.copy())
| import pandas as pd
import numpy as np
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
df = data
family = np.where(
(df["Survived"] + df["Parch"]) >= 1, "Has Family", "No Family"
)
return df.groupby(family)["SibSp"].mean()
def define_test_... | 158 | 158 | 2Pandas | 2 | 2Semantic | 157 |
Problem:
Survived SibSp Parch
0 0 1 0
1 1 1 0
2 1 0 0
3 1 1 1
4 0 0 1
Given the above dataframe, is there an elegant way to groupby with a condition?
I want to split the data into two groups based on the following condition... | def g(df):
family = []
for i in range(len(df)):
if df.loc[i, 'SibSp'] == 0 and df.loc[i, 'Parch'] == 0:
family.append('No Family')
elif df.loc[i, 'SibSp'] == 1 and df.loc[i, 'Parch'] == 1:
family.append('Has Family')
elif df.loc[i, 'SibSp'] == 0 and df.loc[i, 'Par... | import pandas as pd
import numpy as np
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
df = data
family = []
for i in range(len(df)):
if df.loc[i, "SibSp"] == 0 and df.loc[i, "Parch"] == 0:
family.append("No Family")
elif df... | 159 | 159 | 2Pandas | 2 | 0Difficult-Rewrite | 157 |
Problem:
How do I apply sort to a pandas groupby operation? The command below returns an error saying that 'bool' object is not callable
import pandas as pd
df.groupby('cokey').sort('A')
cokey A B
11168155 18 56
11168155 0 18
11168155 56 96
11168156 96 152
11168156 0 96
desired:
... | def g(df):
return df.groupby('cokey').apply(pd.DataFrame.sort_values, 'A')
result = g(df.copy())
| import pandas as pd
import numpy as np
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
df = data
return df.groupby("cokey").apply(pd.DataFrame.sort_values, "A")
def define_test_input(test_case_id):
if test_case_id == 1:
df = pd.DataFrame(
... | 160 | 160 | 2Pandas | 2 | 1Origin | 160 |
Problem:
How do I apply sort to a pandas groupby operation? The command below returns an error saying that 'bool' object is not callable
import pandas as pd
df.groupby('cokey').sort('A')
cokey A B
11168155 18 56
11168155 0 18
11168155 56 96
11168156 96 152
11168156 0 96
desired:
... | def g(df):
return df.groupby('cokey').apply(pd.DataFrame.sort_values, 'A', ascending=False)
result = g(df.copy())
| import pandas as pd
import numpy as np
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
df = data
return df.groupby("cokey").apply(pd.DataFrame.sort_values, "A", ascending=False)
def define_test_input(test_case_id):
if test_case_id == 1:
df = pd.Da... | 161 | 161 | 2Pandas | 2 | 2Semantic | 160 |
Problem:
I get how to use pd.MultiIndex.from_tuples() in order to change something like
Value
(A,a) 1
(B,a) 2
(B,b) 3
into
Value
Caps Lower
A a 1
B a 2
B b 3
But how do I change column tuples in the form
(A, a) (A, b) (B,a) (B,b)
index
1 ... | def g(df):
df.columns = pd.MultiIndex.from_tuples(df.columns, names=['Caps','Lower'])
return df
df = g(df.copy())
| import pandas as pd
import numpy as np
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
df = data
df.columns = pd.MultiIndex.from_tuples(df.columns, names=["Caps", "Lower"])
return df
def define_test_input(test_case_id):
if test_case_id == 1:
... | 162 | 162 | 2Pandas | 1 | 1Origin | 162 |
Problem:
I get how to use pd.MultiIndex.from_tuples() in order to change something like
Value
(A,a) 1
(B,a) 2
(B,b) 3
into
Value
Caps Lower
A a 1
B a 2
B b 3
But how do I change column tuples in the form
(A, 1,a) (A, 1,b) (A, 2,a) (A, 2,b)... | def g(df):
df.columns = pd.MultiIndex.from_tuples(df.columns, names=['Caps','Middle','Lower'])
return df
df = g(df.copy())
| import pandas as pd
import numpy as np
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
df = data
df.columns = pd.MultiIndex.from_tuples(
df.columns, names=["Caps", "Middle", "Lower"]
)
return df
def define_test_input(test_case_id):
... | 163 | 163 | 2Pandas | 2 | 2Semantic | 162 |
Problem:
I get how to use pd.MultiIndex.from_tuples() in order to change something like
Value
(A,a) 1
(B,a) 2
(B,b) 3
into
Value
Caps Lower
A a 1
B a 2
B b 3
But how do I change column tuples in the form
(A,a,1) (B,a,1) (A,b,2) (B,b,2)
inde... | def g(df):
df=df[sorted(df.columns.to_list())]
df.columns = pd.MultiIndex.from_tuples(df.columns, names=['Caps','Middle','Lower'])
return df
df = g(df.copy())
| import pandas as pd
import numpy as np
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
df = data
df = df[sorted(df.columns.to_list())]
df.columns = pd.MultiIndex.from_tuples(
df.columns, names=["Caps", "Middle", "Lower"]
)
return df
... | 164 | 164 | 2Pandas | 1 | 0Difficult-Rewrite | 162 |
Problem:
I am struggling with the basic task of constructing a DataFrame of counts by value from a tuple produced by np.unique(arr, return_counts=True), such as:
import numpy as np
import pandas as pd
np.random.seed(123)
birds=np.random.choice(['African Swallow','Dead Parrot','Exploding Penguin'], size=int(5e4))
some... | def g(someTuple):
return pd.DataFrame(np.column_stack(someTuple),columns=['birdType','birdCount'])
result = g(someTuple)
| import pandas as pd
import numpy as np
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
someTuple = data
return pd.DataFrame(
np.column_stack(someTuple), columns=["birdType", "birdCount"]
)
def define_test_input(test_case_id):
if test_case_... | 165 | 165 | 2Pandas | 1 | 1Origin | 165 |
Problem:
Having a pandas data frame as follow:
a b
0 1 12
1 1 13
2 1 23
3 2 22
4 2 23
5 2 24
6 3 30
7 3 35
8 3 55
I want to find the mean standard deviation of column b in each group.
My following code give me 0 for each group.
stdMeann = lambda x: np.std(np.mean(x))
print(pd.Series(data.groupb... | import numpy as np
def g(df):
return df.groupby("a")["b"].agg([np.mean, np.std])
result = g(df.copy())
| import pandas as pd
import numpy as np
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
df = data
return df.groupby("a")["b"].agg([np.mean, np.std])
def define_test_input(test_case_id):
if test_case_id == 1:
df = pd.DataFrame(
{
... | 166 | 166 | 2Pandas | 2 | 1Origin | 166 |
Problem:
Having a pandas data frame as follow:
a b
0 12 1
1 13 1
2 23 1
3 22 2
4 23 2
5 24 2
6 30 3
7 35 3
8 55 3
I want to find the mean standard deviation of column a in each group.
My following code give me 0 for each group.
stdMeann = lambda x: np.std(np.mean(x))
print(pd.Series(data.grou... | import numpy as np
def g(df):
return df.groupby("b")["a"].agg([np.mean, np.std])
result = g(df.copy())
| import pandas as pd
import numpy as np
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
df = data
return df.groupby("b")["a"].agg([np.mean, np.std])
def define_test_input(test_case_id):
if test_case_id == 1:
df = pd.DataFrame(
{
... | 167 | 167 | 2Pandas | 2 | 2Semantic | 166 |
Problem:
Having a pandas data frame as follow:
a b
0 1 12
1 1 13
2 1 23
3 2 22
4 2 23
5 2 24
6 3 30
7 3 35
8 3 55
I want to find the softmax and min-max normalization of column b in each group.
desired output:
a b softmax min-max
0 1 12 1.670066e-05 0.000000
1 1 13 4.539711e... | import numpy as np
def g(df):
softmax = []
min_max = []
for i in range(len(df)):
Min = np.inf
Max = -np.inf
exp_Sum = 0
for j in range(len(df)):
if df.loc[i, 'a'] == df.loc[j, 'a']:
Min = min(Min, df.loc[j, 'b'])
Max = max(Max, df.l... | import pandas as pd
import numpy as np
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
df = data
softmax = []
min_max = []
for i in range(len(df)):
Min = np.inf
Max = -np.inf
exp_Sum = 0
for j in range(len(df... | 168 | 168 | 2Pandas | 2 | 0Difficult-Rewrite | 166 |
Problem:
I have a dataFrame with rows and columns that sum to 0.
A B C D
0 1 1 0 1
1 0 0 0 0
2 1 0 0 1
3 0 1 0 0
4 1 1 0 1
The end result should be
A B D
0 1 1 1
2 1 0 1
3 0 1 0
4 1 1 1
Notice the rows and columns th... | def g(df):
return df.loc[(df.sum(axis=1) != 0), (df.sum(axis=0) != 0)]
result = g(df.copy())
| import pandas as pd
import numpy as np
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
df = data
return df.loc[(df.sum(axis=1) != 0), (df.sum(axis=0) != 0)]
def define_test_input(test_case_id):
if test_case_id == 1:
df = pd.DataFrame(
... | 169 | 169 | 2Pandas | 2 | 1Origin | 169 |
Problem:
I have a dataFrame with rows and columns that sum to 0.
A B C D
0 -1 -1 0 2
1 0 0 0 0
2 1 0 0 1
3 0 1 0 0
4 1 1 0 1
The end result should be
A B D
2 1 0 1
3 0 1 0
4 1 1 1
Notice that the rows and columns with sum of ... | def g(df):
return df.loc[(df.sum(axis=1) != 0), (df.sum(axis=0) != 0)]
result = g(df.copy())
| import pandas as pd
import numpy as np
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
df = data
return df.loc[(df.sum(axis=1) != 0), (df.sum(axis=0) != 0)]
def define_test_input(test_case_id):
if test_case_id == 1:
df = pd.DataFrame(
... | 170 | 170 | 2Pandas | 2 | 3Surface | 169 |
Problem:
I have a dataFrame with rows and columns that max value is 2.
A B C D
0 1 2 0 1
1 0 0 0 0
2 1 0 0 1
3 0 1 2 0
4 1 1 0 1
The end result should be
A D
1 0 0
2 1 1
4 1 1
Notice the rows and columns that had maximum 2 have been removed.
A:
<code>
import pandas as pd
df =... | def g(df):
return df.loc[(df.max(axis=1) != 2), (df.max(axis=0) != 2)]
result = g(df.copy())
| import pandas as pd
import numpy as np
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
df = data
return df.loc[(df.max(axis=1) != 2), (df.max(axis=0) != 2)]
def define_test_input(test_case_id):
if test_case_id == 1:
df = pd.DataFrame(
... | 171 | 171 | 2Pandas | 2 | 2Semantic | 169 |
Problem:
I have a dataFrame with rows and columns that max value is 2.
A B C D
0 1 2 0 1
1 0 0 0 0
2 1 0 0 1
3 0 1 2 0
4 1 1 0 1
The end result should be
A B C D
0 0 0 0 0
1 0 0 0 0
2 1 0 0 1
3 0 0 0 0
4 1 0 0 1
Notice the rows and columns that had maximum 2 have b... | def g(df):
rows = df.max(axis=1) == 2
cols = df.max(axis=0) == 2
df.loc[rows] = 0
df.loc[:,cols] = 0
return df
result = g(df.copy())
| import pandas as pd
import numpy as np
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
df = data
rows = df.max(axis=1) == 2
cols = df.max(axis=0) == 2
df.loc[rows] = 0
df.loc[:, cols] = 0
return df
def define_test_input(test_case_id):
... | 172 | 172 | 2Pandas | 2 | 0Difficult-Rewrite | 169 |
Problem:
I have a Series that looks like:
146tf150p 1.000000
havent 1.000000
home 1.000000
okie 1.000000
thanx 1.000000
er 1.000000
anything 1.000000
lei 1.000000
nite 1.000000
yup 1.000000
thank 1.000000
ok 1.000000
where 1... | import numpy as np
def g(s):
return s.iloc[np.lexsort([s.index, s.values])]
result = g(s.copy())
| import pandas as pd
import numpy as np
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
s = data
return s.iloc[np.lexsort([s.index, s.values])]
def define_test_input(test_case_id):
if test_case_id == 1:
s = pd.Series(
[1, 1, 1, 1, 1... | 173 | 173 | 2Pandas | 2 | 1Origin | 173 |
Problem:
I have a Series that looks like:
146tf150p 1.000000
havent 1.000000
home 1.000000
okie 1.000000
thanx 1.000000
er 1.000000
anything 1.000000
lei 1.000000
nite 1.000000
yup 1.000000
thank 1.000000
ok 1.000000
where 1... | import numpy as np
def g(s):
result = s.iloc[np.lexsort([s.index, s.values])].reset_index(drop=False)
result.columns = ['index',1]
return result
df = g(s.copy())
| import pandas as pd
import numpy as np
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
s = data
result = s.iloc[np.lexsort([s.index, s.values])].reset_index(drop=False)
result.columns = ["index", 1]
return result
def define_test_input(test_case_id):
... | 174 | 174 | 2Pandas | 2 | 2Semantic | 173 |
Problem:
I have this Pandas dataframe (df):
A B
0 1 green
1 2 red
2 s blue
3 3 yellow
4 b black
A type is object.
I'd select the record where A value are integer or numeric to have:
A B
0 1 green
1 2 red
3 3 yellow
Thanks
A:
<code>
import pandas as p... | def g(df):
return df[pd.to_numeric(df.A, errors='coerce').notnull()]
result = g(df.copy())
| import pandas as pd
import numpy as np
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
df = data
return df[pd.to_numeric(df.A, errors="coerce").notnull()]
def define_test_input(test_case_id):
if test_case_id == 1:
df = pd.DataFrame(
... | 175 | 175 | 2Pandas | 1 | 1Origin | 175 |
Problem:
I have this Pandas dataframe (df):
A B
0 1 green
1 2 red
2 s blue
3 3 yellow
4 b black
A type is object.
I'd select the record where A value are string to have:
A B
2 s blue
4 b black
Thanks
A:
<code>
import pandas as pd
df = pd.DataFrame({'A': [1, 2, ... | def g(df):
result = []
for i in range(len(df)):
if type(df.loc[i, 'A']) == str:
result.append(i)
return df.iloc[result]
result = g(df.copy())
| import pandas as pd
import numpy as np
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
df = data
result = []
for i in range(len(df)):
if type(df.loc[i, "A"]) == str:
result.append(i)
return df.iloc[result]
def define_test_i... | 176 | 176 | 2Pandas | 1 | 2Semantic | 175 |
Problem:
How do I find all rows in a pandas DataFrame which have the max value for count column, after grouping by ['Sp','Mt'] columns?
Example 1: the following DataFrame, which I group by ['Sp','Mt']:
Sp Mt Value count
0 MM1 S1 a **3**
1 MM1 S1 n 2
2 MM1 S3 cb **5**
3 MM2 S3 mk ... | def g(df):
return df[df.groupby(['Sp', 'Mt'])['count'].transform(max) == df['count']]
result = g(df.copy())
| import pandas as pd
import numpy as np
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
df = data
return df[df.groupby(["Sp", "Mt"])["count"].transform(max) == df["count"]]
def define_test_input(test_case_id):
if test_case_id == 1:
df = pd.DataFram... | 177 | 177 | 2Pandas | 2 | 1Origin | 177 |
Problem:
How do I find all rows in a pandas DataFrame which have the max value for count column, after grouping by ['Sp','Mt'] columns?
Example 1: the following DataFrame, which I group by ['Sp','Mt']:
Sp Mt Value count
0 MM1 S1 a 2
1 MM1 S1 n **3**
2 MM1 S3 cb **5**
3 MM2 S3 mk ... | def g(df):
return df[df.groupby(['Sp', 'Mt'])['count'].transform(max) == df['count']]
result = g(df.copy())
| import pandas as pd
import numpy as np
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
df = data
return df[df.groupby(["Sp", "Mt"])["count"].transform(max) == df["count"]]
def define_test_input(test_case_id):
if test_case_id == 1:
df = pd.DataFram... | 178 | 178 | 2Pandas | 2 | 3Surface | 177 |
Problem:
How do I find all rows in a pandas DataFrame which have the min value for count column, after grouping by ['Sp','Mt'] columns?
Example 1: the following DataFrame, which I group by ['Sp','Mt']:
Sp Mt Value count
0 MM1 S1 a **3**
1 MM1 S1 n 2
2 MM1 S3 cb **5**
3 MM2 S3 mk ... | def g(df):
return df[df.groupby(['Sp', 'Mt'])['count'].transform(min) == df['count']]
result = g(df.copy())
| import pandas as pd
import numpy as np
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
df = data
return df[df.groupby(["Sp", "Mt"])["count"].transform(min) == df["count"]]
def define_test_input(test_case_id):
if test_case_id == 1:
df = pd.DataFram... | 179 | 179 | 2Pandas | 2 | 2Semantic | 177 |
Problem:
How do I find all rows in a pandas DataFrame which have the max value for count column, after grouping by ['Sp','Value'] columns?
Example 1: the following DataFrame, which I group by ['Sp','Value']:
Sp Value Mt count
0 MM1 S1 a 3
1 MM1 S1 n 2
2 MM1 S3 cb 5
3 MM2 ... | def g(df):
return df[df.groupby(['Sp', 'Value'])['count'].transform(max) == df['count']]
result = g(df.copy())
| import pandas as pd
import numpy as np
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
df = data
return df[df.groupby(["Sp", "Value"])["count"].transform(max) == df["count"]]
def define_test_input(test_case_id):
if test_case_id == 1:
df = pd.DataF... | 180 | 180 | 2Pandas | 1 | 2Semantic | 177 |
Problem:
I'm looking to map the value in a dict to one column in a DataFrame where the key in the dict is equal to a second column in that DataFrame
For example:
If my dict is:
dict = {'abc':'1/2/2003', 'def':'1/5/2017', 'ghi':'4/10/2013'}
and my DataFrame is:
Member Group Date
0 xyz A ... | import numpy as np
def g(dict, df):
df["Date"] = df["Member"].apply(lambda x: dict.get(x)).fillna(np.NAN)
return df
df = g(dict.copy(),df.copy())
| import pandas as pd
import numpy as np
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
data = data
dict, df = data
df["Date"] = df["Member"].apply(lambda x: dict.get(x)).fillna(np.NAN)
return df
def define_test_input(test_case_id):
if test_cas... | 181 | 181 | 2Pandas | 2 | 1Origin | 181 |
Problem:
I'm looking to map the value in a dict to one column in a DataFrame where the key in the dict is equal to a second column in that DataFrame
For example:
If my dict is:
dict = {'abc':'1/2/2003', 'def':'1/5/2017', 'ghi':'4/10/2013'}
and my DataFrame is:
Member Group Date
0 xyz A ... | def g(dict, df):
df["Date"] = df["Member"].apply(lambda x: dict.get(x)).fillna(np.NAN)
for i in range(len(df)):
if df.loc[i, 'Member'] not in dict.keys():
df.loc[i, 'Date'] = '17/8/1926'
return df
df = g(dict.copy(),df.copy())
| import pandas as pd
import numpy as np
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
data = data
dict, df = data
df["Date"] = df["Member"].apply(lambda x: dict.get(x)).fillna(np.NAN)
for i in range(len(df)):
if df.loc[i, "Member"] not in dict... | 182 | 182 | 2Pandas | 2 | 2Semantic | 181 |
Problem:
I'm looking to map the value in a dict to one column in a DataFrame where the key in the dict is equal to a second column in that DataFrame
For example:
If my dict is:
dict = {'abc':'1/2/2003', 'def':'1/5/2017', 'ghi':'4/10/2013'}
and my DataFrame is:
Member Group Date
0 xyz A ... | df["Date"] = df["Member"].apply(lambda x: dict.get(x)).fillna(np.NAN)
result = df
return result
| import pandas as pd
import numpy as np
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
data = data
dict, df = data
df["Date"] = df["Member"].apply(lambda x: dict.get(x)).fillna(np.NAN)
return df
def define_test_input(test_case_id):
if test_cas... | 183 | 183 | 2Pandas | 2 | 3Surface | 181 |
Problem:
I'm looking to map the value in a dict to one column in a DataFrame where the key in the dict is equal to a second column in that DataFrame
For example:
If my dict is:
dict = {'abc':'1/2/2003', 'def':'1/5/2017', 'ghi':'4/10/2013'}
and my DataFrame is:
Member Group Date
0 xyz A ... | def g(dict, df):
df["Date"] = df["Member"].apply(lambda x: dict.get(x)).fillna(np.NAN)
for i in range(len(df)):
if df.loc[i, 'Member'] not in dict.keys():
df.loc[i, 'Date'] = '17/8/1926'
df["Date"] = pd.to_datetime(df["Date"])
df["Date"] = df["Date"].dt.strftime('%d-%b-%Y')
retur... | import pandas as pd
import numpy as np
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
data = data
dict, df = data
df["Date"] = df["Member"].apply(lambda x: dict.get(x)).fillna(np.NAN)
for i in range(len(df)):
if df.loc[i, "Member"] not in dict... | 184 | 184 | 2Pandas | 2 | 0Difficult-Rewrite | 181 |
Problem:
I am trying to groupby counts of dates per month and year in a specific output. I can do it per day but can't get the same output per month/year.
d = ({
'Date' : ['1/1/18','1/1/18','2/1/18','3/1/18','1/2/18','1/3/18','2/1/19','3/1/19'],
'Val' : ['A','B','C','D','A','B','C','D'], ... | def g(df):
df['Date'] = pd.to_datetime(df['Date'], format='%d/%m/%y')
y = df['Date'].dt.year
m = df['Date'].dt.month
df['Count_d'] = df.groupby('Date')['Date'].transform('size')
df['Count_m'] = df.groupby([y, m])['Date'].transform('size')
df['Count_y'] = df.groupby(y)['Date'].transform('size')... | import pandas as pd
import numpy as np
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
df = data
df["Date"] = pd.to_datetime(df["Date"], format="%d/%m/%y")
y = df["Date"].dt.year
m = df["Date"].dt.month
df["Count_d"] = df.groupby("Date")["Date"].tr... | 185 | 185 | 2Pandas | 2 | 1Origin | 185 |
Problem:
I am trying to groupby counts of dates per month and year in a specific output. I can do it per day but can't get the same output per month/year.
d = ({
'Date' : ['1/1/18','1/1/18','2/1/18','3/1/18','1/2/18','1/3/18','2/1/19','3/1/19'],
'Val' : ['A','B','C','D','A','B','C','D'], ... | def g(df):
df['Date'] = pd.to_datetime(df['Date'], format='%d/%m/%y')
y = df['Date'].dt.year
m = df['Date'].dt.month
df['Count_d'] = df.groupby('Date')['Date'].transform('size')
df['Count_m'] = df.groupby([y, m])['Date'].transform('size')
df['Count_y'] = df.groupby(y)['Date'].transform('size')... | import pandas as pd
import numpy as np
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
df = data
df["Date"] = pd.to_datetime(df["Date"], format="%d/%m/%y")
y = df["Date"].dt.year
m = df["Date"].dt.month
df["Count_d"] = df.groupby("Date")["Date"].tr... | 186 | 186 | 2Pandas | 2 | 2Semantic | 185 |
Problem:
I am trying to groupby counts of dates per month and year in a specific output. I can do it per day but can't get the same output per month/year.
d = ({
'Date' : ['1/1/18','1/1/18','2/1/18','3/1/18','1/2/18','1/3/18','2/1/19','3/1/19'],
'Val' : ['A','B','C','D','A','B','C','D'], ... | def g(df):
df['Date'] = pd.to_datetime(df['Date'], format='%d/%m/%y')
y = df['Date'].dt.year
m = df['Date'].dt.month
w = df['Date'].dt.weekday
df['Count_d'] = df.groupby('Date')['Date'].transform('size')
df['Count_m'] = df.groupby([y, m])['Date'].transform('size')
df['Count_y'] = df.groupb... | import pandas as pd
import numpy as np
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
df = data
df["Date"] = pd.to_datetime(df["Date"], format="%d/%m/%y")
y = df["Date"].dt.year
m = df["Date"].dt.month
w = df["Date"].dt.weekday
df["Count_d... | 187 | 187 | 2Pandas | 2 | 0Difficult-Rewrite | 185 |
Problem:
I have a dataframe, e.g:
Date B C
20.07.2018 10 8
20.07.2018 1 0
21.07.2018 0 1
21.07.2018 1 0
How can I count the zero and non-zero values for each column for each date?
Using .sum() doesn't help me because it will sum t... | def g(df):
df1 = df.groupby('Date').agg(lambda x: x.eq(0).sum())
df2 = df.groupby('Date').agg(lambda x: x.ne(0).sum())
return df1, df2
result1, result2 = g(df.copy())
| import pandas as pd
import numpy as np
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
df = data
df1 = df.groupby("Date").agg(lambda x: x.eq(0).sum())
df2 = df.groupby("Date").agg(lambda x: x.ne(0).sum())
return df1, df2
def define_test_input(test_cas... | 188 | 188 | 2Pandas | 2 | 1Origin | 188 |
Problem:
I have a dataframe, e.g:
Date B C
20.07.2018 10 8
20.07.2018 1 0
21.07.2018 0 1
21.07.2018 1 0
How can I count the even and odd values for each column for each date?
Using .sum() doesn't help me because it will sum all th... | def g(df):
df1 = df.groupby('Date').agg(lambda x: (x%2==0).sum())
df2 = df.groupby('Date').agg(lambda x: (x%2==1).sum())
return df1, df2
result1, result2 = g(df.copy())
| import pandas as pd
import numpy as np
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
df = data
df1 = df.groupby("Date").agg(lambda x: (x % 2 == 0).sum())
df2 = df.groupby("Date").agg(lambda x: (x % 2 == 1).sum())
return df1, df2
def define_test_inpu... | 189 | 189 | 2Pandas | 2 | 2Semantic | 188 |
Problem:
Was trying to generate a pivot table with multiple "values" columns. I know I can use aggfunc to aggregate values the way I want to, but what if I don't want to sum or avg both columns but instead I want sum of one column while mean of the other one. So is it possible to do so using pandas?
df = pd.DataFrame... | def g(df):
return pd.pivot_table(df, values=['D','E'], index=['B'], aggfunc={'D':np.sum, 'E':np.mean})
result = g(df.copy())
| import pandas as pd
import numpy as np
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
df = data
return pd.pivot_table(
df, values=["D", "E"], index=["B"], aggfunc={"D": np.sum, "E": np.mean}
)
def define_test_input(test_case_id):
if test_... | 190 | 190 | 2Pandas | 1 | 1Origin | 190 |
Problem:
I have a dataframe:
df = pd.DataFrame({
'A' : ['one', 'one', 'two', 'three'] * 6,
'B' : ['A', 'B', 'C'] * 8,
'C' : ['foo', 'foo', 'foo', 'bar', 'bar', 'bar'] * 4,
'D' : np.random.arange(24),
'E' : np.random.arange(24)
})
Now this will get a pivot table with sum:
pd.pivot_table(df, values=['D','E'], rows=['... | def g(df):
return pd.pivot_table(df, values=['D','E'], index=['B'], aggfunc={'D':np.sum, 'E':np.mean})
result = g(df.copy())
| import pandas as pd
import numpy as np
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
df = data
return pd.pivot_table(
df, values=["D", "E"], index=["B"], aggfunc={"D": np.sum, "E": np.mean}
)
def define_test_input(test_case_id):
if test_... | 191 | 191 | 2Pandas | 1 | 3Surface | 190 |
Problem:
Was trying to generate a pivot table with multiple "values" columns. I know I can use aggfunc to aggregate values the way I want to, but what if I don't want to sum or avg both columns but instead I want sum of one column while mean of the other one. So is it possible to do so using pandas?
df = pd.DataFrame... | def g(df):
return pd.pivot_table(df, values=['D','E'], index=['B'], aggfunc={'D':np.sum, 'E':np.mean})
result = g(df.copy())
| import pandas as pd
import numpy as np
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
df = data
return pd.pivot_table(
df, values=["D", "E"], index=["B"], aggfunc={"D": np.sum, "E": np.mean}
)
def define_test_input(test_case_id):
if test_... | 192 | 192 | 2Pandas | 1 | 3Surface | 190 |
Problem:
Was trying to generate a pivot table with multiple "values" columns. I know I can use aggfunc to aggregate values the way I want to, but what if I don't want to max or min both columns but instead I want max of one column while min of the other one. So is it possible to do so using pandas?
df = pd.DataFrame(... | def g(df):
return pd.pivot_table(df, values=['D','E'], index=['B'], aggfunc={'D':np.max, 'E':np.min})
result = g(df.copy())
| import pandas as pd
import numpy as np
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
df = data
return pd.pivot_table(
df, values=["D", "E"], index=["B"], aggfunc={"D": np.max, "E": np.min}
)
def define_test_input(test_case_id):
if test_c... | 193 | 193 | 2Pandas | 1 | 2Semantic | 190 |
Problem:
What is an efficient way of splitting a column into multiple rows using dask dataframe? For example, let's say I have a csv file which I read using dask to produce the following dask dataframe:
id var1 var2
1 A Z,Y
2 B X
3 C W,U,V
I would like to convert it to:
id var1 var2
1 A Z
1 A Y
2 ... | def g(df):
return df.drop('var2', axis=1).join(df.var2.str.split(',', expand=True).stack().
reset_index(drop=True, level=1).rename('var2'))
result = g(df.copy())
| import pandas as pd
import numpy as np
import copy
import tokenize, io
def generate_test_case(test_case_id):
def generate_ans(data):
df = data
return df.drop("var2", axis=1).join(
df.var2.str.split(",", expand=True)
.stack()
.reset_index(drop=True, level=1)
... | 194 | 194 | 2Pandas | 2 | 1Origin | 194 |
Problem:
What is an efficient way of splitting a column into multiple rows using dask dataframe? For example, let's say I have a csv file which I read using dask to produce the following dask dataframe:
var1 var2
1 A Z,Y
2 B X
3 C W,U,V
I would like to convert it to:
var1 var2
0 A Z
1 A Y... | def g(df):
return df.join(pd.DataFrame(df.var2.str.split(',', expand=True).stack().reset_index(level=1, drop=True),columns=['var2 '])).\
drop('var2',1).rename(columns=str.strip).reset_index(drop=True)
result = g(df.copy())
| import pandas as pd
import numpy as np
import copy
import tokenize, io
def generate_test_case(test_case_id):
def generate_ans(data):
df = data
return (
df.join(
pd.DataFrame(
df.var2.str.split(",", expand=True)
.stack()
... | 195 | 195 | 2Pandas | 2 | 2Semantic | 194 |
Problem:
What is an efficient way of splitting a column into multiple rows using dask dataframe? For example, let's say I have a csv file which I read using dask to produce the following dask dataframe:
var1 var2
1 A Z-Y
2 B X
3 C W-U-V
I would like to convert it to:
var1 var2
0 A Z
1 A Y... | def g(df):
return df.join(pd.DataFrame(df.var2.str.split('-', expand=True).stack().reset_index(level=1, drop=True),columns=['var2 '])).\
drop('var2',1).rename(columns=str.strip).reset_index(drop=True)
result = g(df.copy())
| import pandas as pd
import numpy as np
import copy
import tokenize, io
def generate_test_case(test_case_id):
def generate_ans(data):
df = data
return (
df.join(
pd.DataFrame(
df.var2.str.split("-", expand=True)
.stack()
... | 196 | 196 | 2Pandas | 2 | 0Difficult-Rewrite | 194 |
Problem:
I am trying to get count of special chars in column using Pandas.
But not getting desired output.
My .txt file is:
str
Aa
Bb
?? ?
x;
###
My Code is :
import pandas as pd
df=pd.read_csv('inn.txt',sep='\t')
def count_special_char(string):
special_char = 0
for i in range(len(string)):
if(string[... | import numpy as np
def g(df):
df["new"] = df.apply(lambda p: sum( not q.isalpha() for q in p["str"] ), axis=1)
df["new"] = df["new"].replace(0, np.NAN)
return df
df = g(df.copy())
| import pandas as pd
import numpy as np
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
df = data
df["new"] = df.apply(lambda p: sum(not q.isalpha() for q in p["str"]), axis=1)
df["new"] = df["new"].replace(0, np.NAN)
return df
def define_test_input(te... | 197 | 197 | 2Pandas | 2 | 1Origin | 197 |
Problem:
I am trying to get count of letter chars in column using Pandas.
But not getting desired output.
My .txt file is:
str
Aa
Bb
?? ?
x;
###
My Code is :
import pandas as pd
df=pd.read_csv('inn.txt',sep='\t')
def count_special_char(string):
special_char = 0
for i in range(len(string)):
if(string[i... | def g(df):
df["new"] = df.apply(lambda p: sum(q.isalpha() for q in p["str"] ), axis=1)
return df
df = g(df.copy())
| import pandas as pd
import numpy as np
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
df = data
df["new"] = df.apply(lambda p: sum(q.isalpha() for q in p["str"]), axis=1)
return df
def define_test_input(test_case_id):
if test_case_id == 1:
... | 198 | 198 | 2Pandas | 2 | 2Semantic | 197 |
Problem:
I have a data frame with one (string) column and I'd like to split it into two (string) columns, with one column header as 'fips' and the other 'row'
My dataframe df looks like this:
row
0 00000 UNITED STATES
1 01000 ALABAMA
2 01001 Autauga County, AL
3 01003 Baldwin County, AL
4 01005 Barbour County, AL
I... | def g(df):
return pd.DataFrame(df.row.str.split(' ', 1).tolist(), columns=['fips', 'row'])
df = g(df.copy())
| import pandas as pd
import numpy as np
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
df = data
return pd.DataFrame(df.row.str.split(" ", 1).tolist(), columns=["fips", "row"])
def define_test_input(test_case_id):
if test_case_id == 1:
df = pd.Dat... | 199 | 199 | 2Pandas | 2 | 1Origin | 199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.