prompt
stringlengths
105
4.73k
reference_code
stringlengths
11
774
metadata
dict
code_context
stringlengths
746
120k
Problem: In pandas, how do I replace &AMP; with '&' from all columns where &AMP could be in any position in a string? For example, in column Title if there is a value 'Good &AMP; bad', how do I replace it with 'Good & bad'? A: <code> import pandas as pd df = pd.DataFrame({'A': ['Good &AMP; bad', 'BB', 'CC', 'DD', '...
def g(df): return df.replace('&AMP;','&', regex=True) df = g(df.copy())
{ "problem_id": 100, "library_problem_id": 100, "library": "Pandas", "test_case_cnt": 1, "perturbation_type": "Origin", "perturbation_origin_id": 100 }
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("&AMP;", "&", regex=True) def define_test_input(test_case_id): if test_case_id == 1: df = pd.DataFrame( { ...
Problem: In pandas, how do I replace &LT; with '<' from all columns where &LT could be in any position in a string? For example, in column Title if there is a value 'Good &LT; bad', how do I replace it with 'Good < bad'? A: <code> import pandas as pd df = pd.DataFrame({'A': ['Good &LT bad', 'BB', 'CC', 'DD', 'Good ...
def g(df): return df.replace('&LT;','<', regex=True) df = g(df.copy())
{ "problem_id": 101, "library_problem_id": 101, "library": "Pandas", "test_case_cnt": 1, "perturbation_type": "Semantic", "perturbation_origin_id": 100 }
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("&LT;", "<", regex=True) def define_test_input(test_case_id): if test_case_id == 1: df = pd.DataFrame( { ...
Problem: In pandas, how do I replace &AMP; with '&' from all columns where &AMP could be in any position in a string? For example, in column Title if there is a value 'Good &AMP; bad', how do I replace it with 'Good & bad'? A: <code> import pandas as pd example_df = pd.DataFrame({'A': ['Good &AMP; bad', 'BB', 'CC', ...
result = df.replace('&AMP;','&', regex=True) return result
{ "problem_id": 102, "library_problem_id": 102, "library": "Pandas", "test_case_cnt": 1, "perturbation_type": "Surface", "perturbation_origin_id": 100 }
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("&AMP;", "&", regex=True) def define_test_input(test_case_id): if test_case_id == 1: df = pd.DataFrame( { ...
Problem: In pandas, how do I replace &AMP;,&LT;,&GT; with '&''<''>' from all columns where &AMP could be in any position in a string? For example, in column Title if there is a value 'Good &AMP; bad', how do I replace it with 'Good & bad'? A: <code> import pandas as pd df = pd.DataFrame({'A': ['Good &AMP; bad', 'BB...
def g(df): df.replace('&AMP;', '&', regex=True, inplace=True) df.replace('&LT;', '<', regex=True, inplace=True) df.replace('&GT;', '>', regex=True, inplace=True) return df df = g(df.copy())
{ "problem_id": 103, "library_problem_id": 103, "library": "Pandas", "test_case_cnt": 1, "perturbation_type": "Difficult-Rewrite", "perturbation_origin_id": 100 }
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("&AMP;", "&", regex=True, inplace=True) df.replace("&LT;", "<", regex=True, inplace=True) df.replace("&GT;", ">", regex=True, inplace=True) ...
Problem: In pandas, how do I replace &AMP; with '&' from all columns where &AMP could be in any position in a string?Then please evaluate this expression. For example, in column Title if there is a value '1 &AMP; 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 '&AMP;' in df.loc[i, col]: df.loc[i, col] = df.loc[i, col].replace('&AMP;', '&') df.loc[i, col] = df.loc[i, col]+' = '+str(eval(df.loc[i, col])) df.re...
{ "problem_id": 104, "library_problem_id": 104, "library": "Pandas", "test_case_cnt": 1, "perturbation_type": "Difficult-Rewrite", "perturbation_origin_id": 100 }
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 "&AMP;" in df.loc[i, col]: d...
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())
{ "problem_id": 105, "library_problem_id": 105, "library": "Pandas", "test_case_cnt": 1, "perturbation_type": "Origin", "perturbation_origin_id": 105 }
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...
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())
{ "problem_id": 106, "library_problem_id": 106, "library": "Pandas", "test_case_cnt": 1, "perturbation_type": "Semantic", "perturbation_origin_id": 105 }
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"] ...
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 += ' '+...
{ "problem_id": 107, "library_problem_id": 107, "library": "Pandas", "test_case_cnt": 1, "perturbation_type": "Difficult-Rewrite", "perturbation_origin_id": 105 }
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....
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())
{ "problem_id": 108, "library_problem_id": 108, "library": "Pandas", "test_case_cnt": 2, "perturbation_type": "Origin", "perturbation_origin_id": 108 }
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...
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())
{ "problem_id": 109, "library_problem_id": 109, "library": "Pandas", "test_case_cnt": 2, "perturbation_type": "Semantic", "perturbation_origin_id": 108 }
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...
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())
{ "problem_id": 110, "library_problem_id": 110, "library": "Pandas", "test_case_cnt": 2, "perturbation_type": "Origin", "perturbation_origin_id": 110 }
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...
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())
{ "problem_id": 111, "library_problem_id": 111, "library": "Pandas", "test_case_cnt": 2, "perturbation_type": "Semantic", "perturbation_origin_id": 110 }
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...
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())
{ "problem_id": 112, "library_problem_id": 112, "library": "Pandas", "test_case_cnt": 2, "perturbation_type": "Origin", "perturbation_origin_id": 112 }
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...
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())
{ "problem_id": 113, "library_problem_id": 113, "library": "Pandas", "test_case_cnt": 2, "perturbation_type": "Semantic", "perturbation_origin_id": 112 }
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(...
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
{ "problem_id": 114, "library_problem_id": 114, "library": "Pandas", "test_case_cnt": 2, "perturbation_type": "Surface", "perturbation_origin_id": 112 }
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...
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())
{ "problem_id": 115, "library_problem_id": 115, "library": "Pandas", "test_case_cnt": 2, "perturbation_type": "Origin", "perturbation_origin_id": 115 }
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: ...
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())
{ "problem_id": 116, "library_problem_id": 116, "library": "Pandas", "test_case_cnt": 2, "perturbation_type": "Semantic", "perturbation_origin_id": 115 }
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: ...
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)
{ "problem_id": 117, "library_problem_id": 117, "library": "Pandas", "test_case_cnt": 1, "perturbation_type": "Origin", "perturbation_origin_id": 117 }
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( ...
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)
{ "problem_id": 118, "library_problem_id": 118, "library": "Pandas", "test_case_cnt": 1, "perturbation_type": "Surface", "perturbation_origin_id": 117 }
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( ...
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)
{ "problem_id": 119, "library_problem_id": 119, "library": "Pandas", "test_case_cnt": 1, "perturbation_type": "Semantic", "perturbation_origin_id": 117 }
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(...
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
{ "problem_id": 120, "library_problem_id": 120, "library": "Pandas", "test_case_cnt": 1, "perturbation_type": "Difficult-Rewrite", "perturbation_origin_id": 117 }
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( ...
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...
{ "problem_id": 121, "library_problem_id": 121, "library": "Pandas", "test_case_cnt": 2, "perturbation_type": "Origin", "perturbation_origin_id": 121 }
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 ...
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...
{ "problem_id": 122, "library_problem_id": 122, "library": "Pandas", "test_case_cnt": 2, "perturbation_type": "Semantic", "perturbation_origin_id": 121 }
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 ...
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())
{ "problem_id": 123, "library_problem_id": 123, "library": "Pandas", "test_case_cnt": 2, "perturbation_type": "Origin", "perturbation_origin_id": 123 }
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 ...
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())
{ "problem_id": 124, "library_problem_id": 124, "library": "Pandas", "test_case_cnt": 2, "perturbation_type": "Semantic", "perturbation_origin_id": 123 }
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 ...
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())
{ "problem_id": 125, "library_problem_id": 125, "library": "Pandas", "test_case_cnt": 2, "perturbation_type": "Difficult-Rewrite", "perturbation_origin_id": 123 }
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): ...
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())
{ "problem_id": 126, "library_problem_id": 126, "library": "Pandas", "test_case_cnt": 2, "perturbation_type": "Difficult-Rewrite", "perturbation_origin_id": 123 }
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...
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())
{ "problem_id": 127, "library_problem_id": 127, "library": "Pandas", "test_case_cnt": 2, "perturbation_type": "Origin", "perturbation_origin_id": 127 }
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...
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())
{ "problem_id": 128, "library_problem_id": 128, "library": "Pandas", "test_case_cnt": 2, "perturbation_type": "Semantic", "perturbation_origin_id": 127 }
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...
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 ...
{ "problem_id": 129, "library_problem_id": 129, "library": "Pandas", "test_case_cnt": 2, "perturbation_type": "Difficult-Rewrite", "perturbation_origin_id": 127 }
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"]: ...
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())
{ "problem_id": 130, "library_problem_id": 130, "library": "Pandas", "test_case_cnt": 2, "perturbation_type": "Origin", "perturbation_origin_id": 130 }
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...
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,...
{ "problem_id": 131, "library_problem_id": 131, "library": "Pandas", "test_case_cnt": 2, "perturbation_type": "Semantic", "perturbation_origin_id": 130 }
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...
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
{ "problem_id": 132, "library_problem_id": 132, "library": "Pandas", "test_case_cnt": 2, "perturbation_type": "Surface", "perturbation_origin_id": 130 }
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...
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())
{ "problem_id": 133, "library_problem_id": 133, "library": "Pandas", "test_case_cnt": 2, "perturbation_type": "Difficult-Rewrite", "perturbation_origin_id": 130 }
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")] ...
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...
{ "problem_id": 134, "library_problem_id": 134, "library": "Pandas", "test_case_cnt": 2, "perturbation_type": "Difficult-Rewrite", "perturbation_origin_id": 130 }
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 - ...
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())
{ "problem_id": 135, "library_problem_id": 135, "library": "Pandas", "test_case_cnt": 1, "perturbation_type": "Origin", "perturbation_origin_id": 135 }
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...
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())
{ "problem_id": 136, "library_problem_id": 136, "library": "Pandas", "test_case_cnt": 2, "perturbation_type": "Surface", "perturbation_origin_id": 135 }
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...
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())
{ "problem_id": 137, "library_problem_id": 137, "library": "Pandas", "test_case_cnt": 2, "perturbation_type": "Semantic", "perturbation_origin_id": 135 }
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...
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())
{ "problem_id": 138, "library_problem_id": 138, "library": "Pandas", "test_case_cnt": 2, "perturbation_type": "Difficult-Rewrite", "perturbation_origin_id": 135 }
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...
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)
{ "problem_id": 139, "library_problem_id": 139, "library": "Pandas", "test_case_cnt": 2, "perturbation_type": "Origin", "perturbation_origin_id": 139 }
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...
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)
{ "problem_id": 140, "library_problem_id": 140, "library": "Pandas", "test_case_cnt": 2, "perturbation_type": "Semantic", "perturbation_origin_id": 139 }
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...
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())
{ "problem_id": 141, "library_problem_id": 141, "library": "Pandas", "test_case_cnt": 2, "perturbation_type": "Origin", "perturbation_origin_id": 141 }
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"...
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())
{ "problem_id": 142, "library_problem_id": 142, "library": "Pandas", "test_case_cnt": 2, "perturbation_type": "Semantic", "perturbation_origin_id": 141 }
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 ...
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())
{ "problem_id": 143, "library_problem_id": 143, "library": "Pandas", "test_case_cnt": 3, "perturbation_type": "Origin", "perturbation_origin_id": 143 }
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...
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())
{ "problem_id": 144, "library_problem_id": 144, "library": "Pandas", "test_case_cnt": 3, "perturbation_type": "Surface", "perturbation_origin_id": 143 }
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...
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())
{ "problem_id": 145, "library_problem_id": 145, "library": "Pandas", "test_case_cnt": 3, "perturbation_type": "Surface", "perturbation_origin_id": 143 }
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...
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())
{ "problem_id": 146, "library_problem_id": 146, "library": "Pandas", "test_case_cnt": 3, "perturbation_type": "Semantic", "perturbation_origin_id": 143 }
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...
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())
{ "problem_id": 147, "library_problem_id": 147, "library": "Pandas", "test_case_cnt": 3, "perturbation_type": "Difficult-Rewrite", "perturbation_origin_id": 143 }
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(...
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())
{ "problem_id": 148, "library_problem_id": 148, "library": "Pandas", "test_case_cnt": 2, "perturbation_type": "Origin", "perturbation_origin_id": 148 }
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": [...
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())
{ "problem_id": 149, "library_problem_id": 149, "library": "Pandas", "test_case_cnt": 2, "perturbation_type": "Semantic", "perturbation_origin_id": 148 }
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": [...
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())
{ "problem_id": 150, "library_problem_id": 150, "library": "Pandas", "test_case_cnt": 2, "perturbation_type": "Difficult-Rewrite", "perturbation_origin_id": 148 }
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 = { ...
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...
{ "problem_id": 151, "library_problem_id": 151, "library": "Pandas", "test_case_cnt": 2, "perturbation_type": "Origin", "perturbation_origin_id": 151 }
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...
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==...
{ "problem_id": 152, "library_problem_id": 152, "library": "Pandas", "test_case_cnt": 2, "perturbation_type": "Semantic", "perturbation_origin_id": 151 }
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...
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...
{ "problem_id": 153, "library_problem_id": 153, "library": "Pandas", "test_case_cnt": 2, "perturbation_type": "Difficult-Rewrite", "perturbation_origin_id": 151 }
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(...
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==...
{ "problem_id": 154, "library_problem_id": 154, "library": "Pandas", "test_case_cnt": 2, "perturbation_type": "Difficult-Rewrite", "perturbation_origin_id": 151 }
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(...
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'...
{ "problem_id": 155, "library_problem_id": 155, "library": "Pandas", "test_case_cnt": 1, "perturbation_type": "Origin", "perturbation_origin_id": 155 }
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(...
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())
{ "problem_id": 156, "library_problem_id": 156, "library": "Pandas", "test_case_cnt": 2, "perturbation_type": "Origin", "perturbation_origin_id": 156 }
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( ...
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())
{ "problem_id": 157, "library_problem_id": 157, "library": "Pandas", "test_case_cnt": 2, "perturbation_type": "Origin", "perturbation_origin_id": 157 }
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): ...
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())
{ "problem_id": 158, "library_problem_id": 158, "library": "Pandas", "test_case_cnt": 2, "perturbation_type": "Semantic", "perturbation_origin_id": 157 }
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_...
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...
{ "problem_id": 159, "library_problem_id": 159, "library": "Pandas", "test_case_cnt": 2, "perturbation_type": "Difficult-Rewrite", "perturbation_origin_id": 157 }
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...
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())
{ "problem_id": 160, "library_problem_id": 160, "library": "Pandas", "test_case_cnt": 2, "perturbation_type": "Origin", "perturbation_origin_id": 160 }
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( ...
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())
{ "problem_id": 161, "library_problem_id": 161, "library": "Pandas", "test_case_cnt": 2, "perturbation_type": "Semantic", "perturbation_origin_id": 160 }
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...
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())
{ "problem_id": 162, "library_problem_id": 162, "library": "Pandas", "test_case_cnt": 1, "perturbation_type": "Origin", "perturbation_origin_id": 162 }
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: ...
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())
{ "problem_id": 163, "library_problem_id": 163, "library": "Pandas", "test_case_cnt": 2, "perturbation_type": "Semantic", "perturbation_origin_id": 162 }
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): ...
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())
{ "problem_id": 164, "library_problem_id": 164, "library": "Pandas", "test_case_cnt": 1, "perturbation_type": "Difficult-Rewrite", "perturbation_origin_id": 162 }
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 ...
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)
{ "problem_id": 165, "library_problem_id": 165, "library": "Pandas", "test_case_cnt": 1, "perturbation_type": "Origin", "perturbation_origin_id": 165 }
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_...
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())
{ "problem_id": 166, "library_problem_id": 166, "library": "Pandas", "test_case_cnt": 2, "perturbation_type": "Origin", "perturbation_origin_id": 166 }
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( { ...
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())
{ "problem_id": 167, "library_problem_id": 167, "library": "Pandas", "test_case_cnt": 2, "perturbation_type": "Semantic", "perturbation_origin_id": 166 }
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( { ...
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...
{ "problem_id": 168, "library_problem_id": 168, "library": "Pandas", "test_case_cnt": 2, "perturbation_type": "Difficult-Rewrite", "perturbation_origin_id": 166 }
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...
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())
{ "problem_id": 169, "library_problem_id": 169, "library": "Pandas", "test_case_cnt": 2, "perturbation_type": "Origin", "perturbation_origin_id": 169 }
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( ...
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())
{ "problem_id": 170, "library_problem_id": 170, "library": "Pandas", "test_case_cnt": 2, "perturbation_type": "Surface", "perturbation_origin_id": 169 }
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( ...
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())
{ "problem_id": 171, "library_problem_id": 171, "library": "Pandas", "test_case_cnt": 2, "perturbation_type": "Semantic", "perturbation_origin_id": 169 }
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( ...
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())
{ "problem_id": 172, "library_problem_id": 172, "library": "Pandas", "test_case_cnt": 2, "perturbation_type": "Difficult-Rewrite", "perturbation_origin_id": 169 }
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): ...
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())
{ "problem_id": 173, "library_problem_id": 173, "library": "Pandas", "test_case_cnt": 2, "perturbation_type": "Origin", "perturbation_origin_id": 173 }
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...
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())
{ "problem_id": 174, "library_problem_id": 174, "library": "Pandas", "test_case_cnt": 2, "perturbation_type": "Semantic", "perturbation_origin_id": 173 }
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): ...
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())
{ "problem_id": 175, "library_problem_id": 175, "library": "Pandas", "test_case_cnt": 1, "perturbation_type": "Origin", "perturbation_origin_id": 175 }
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( ...
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())
{ "problem_id": 176, "library_problem_id": 176, "library": "Pandas", "test_case_cnt": 1, "perturbation_type": "Semantic", "perturbation_origin_id": 175 }
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...
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())
{ "problem_id": 177, "library_problem_id": 177, "library": "Pandas", "test_case_cnt": 2, "perturbation_type": "Origin", "perturbation_origin_id": 177 }
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...
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())
{ "problem_id": 178, "library_problem_id": 178, "library": "Pandas", "test_case_cnt": 2, "perturbation_type": "Surface", "perturbation_origin_id": 177 }
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...
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())
{ "problem_id": 179, "library_problem_id": 179, "library": "Pandas", "test_case_cnt": 2, "perturbation_type": "Semantic", "perturbation_origin_id": 177 }
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...
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())
{ "problem_id": 180, "library_problem_id": 180, "library": "Pandas", "test_case_cnt": 1, "perturbation_type": "Semantic", "perturbation_origin_id": 177 }
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...
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())
{ "problem_id": 181, "library_problem_id": 181, "library": "Pandas", "test_case_cnt": 2, "perturbation_type": "Origin", "perturbation_origin_id": 181 }
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...
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())
{ "problem_id": 182, "library_problem_id": 182, "library": "Pandas", "test_case_cnt": 2, "perturbation_type": "Semantic", "perturbation_origin_id": 181 }
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...
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
{ "problem_id": 183, "library_problem_id": 183, "library": "Pandas", "test_case_cnt": 2, "perturbation_type": "Surface", "perturbation_origin_id": 181 }
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...
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...
{ "problem_id": 184, "library_problem_id": 184, "library": "Pandas", "test_case_cnt": 2, "perturbation_type": "Difficult-Rewrite", "perturbation_origin_id": 181 }
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...
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')...
{ "problem_id": 185, "library_problem_id": 185, "library": "Pandas", "test_case_cnt": 2, "perturbation_type": "Origin", "perturbation_origin_id": 185 }
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...
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')...
{ "problem_id": 186, "library_problem_id": 186, "library": "Pandas", "test_case_cnt": 2, "perturbation_type": "Semantic", "perturbation_origin_id": 185 }
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...
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...
{ "problem_id": 187, "library_problem_id": 187, "library": "Pandas", "test_case_cnt": 2, "perturbation_type": "Difficult-Rewrite", "perturbation_origin_id": 185 }
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...
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())
{ "problem_id": 188, "library_problem_id": 188, "library": "Pandas", "test_case_cnt": 2, "perturbation_type": "Origin", "perturbation_origin_id": 188 }
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...
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())
{ "problem_id": 189, "library_problem_id": 189, "library": "Pandas", "test_case_cnt": 2, "perturbation_type": "Semantic", "perturbation_origin_id": 188 }
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...
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())
{ "problem_id": 190, "library_problem_id": 190, "library": "Pandas", "test_case_cnt": 1, "perturbation_type": "Origin", "perturbation_origin_id": 190 }
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_...
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())
{ "problem_id": 191, "library_problem_id": 191, "library": "Pandas", "test_case_cnt": 1, "perturbation_type": "Surface", "perturbation_origin_id": 190 }
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_...
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())
{ "problem_id": 192, "library_problem_id": 192, "library": "Pandas", "test_case_cnt": 1, "perturbation_type": "Surface", "perturbation_origin_id": 190 }
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_...
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())
{ "problem_id": 193, "library_problem_id": 193, "library": "Pandas", "test_case_cnt": 1, "perturbation_type": "Semantic", "perturbation_origin_id": 190 }
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...
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())
{ "problem_id": 194, "library_problem_id": 194, "library": "Pandas", "test_case_cnt": 2, "perturbation_type": "Origin", "perturbation_origin_id": 194 }
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) ...
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())
{ "problem_id": 195, "library_problem_id": 195, "library": "Pandas", "test_case_cnt": 2, "perturbation_type": "Semantic", "perturbation_origin_id": 194 }
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() ...
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())
{ "problem_id": 196, "library_problem_id": 196, "library": "Pandas", "test_case_cnt": 2, "perturbation_type": "Difficult-Rewrite", "perturbation_origin_id": 194 }
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() ...
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())
{ "problem_id": 197, "library_problem_id": 197, "library": "Pandas", "test_case_cnt": 2, "perturbation_type": "Origin", "perturbation_origin_id": 197 }
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...
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())
{ "problem_id": 198, "library_problem_id": 198, "library": "Pandas", "test_case_cnt": 2, "perturbation_type": "Semantic", "perturbation_origin_id": 197 }
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: ...
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())
{ "problem_id": 199, "library_problem_id": 199, "library": "Pandas", "test_case_cnt": 2, "perturbation_type": "Origin", "perturbation_origin_id": 199 }
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...