Pandas 从行索引和 return 值到新列查找特定字符串
Pandas find specific string from row index and return value to new column
我正在创建一个新专栏,该专栏的依据是学生是否曾经根据 'file' 专栏重新测试过某个科目:
这是行数据:
这就是我想要实现的方式:
这是我的代码:
import pandas as pd
df = pd.DataFrame(columns=['file', 'class', 'student', 'subject', 'scores'],
data=[['re_test', 'A', 'John', 'Math', 60],
['first_test', 'A', 'Scott', 'Math', 75],
['first_test', 'A', 'Mary', 'Math', 80],
['re_test', 'B', 'Jack', 'Math', 70],
['first_test', 'B', 'Mina', 'Math', 75],
['first_test', 'B', 'James', 'Math', 95]])
df_math= df.pivot_table(index= ['class', 'student', 'file'],
values=['subject'], aggfunc=['count'], fill_value = 0)
def retest_check(res):
res_check = []
if 're' in res['file']:
res_check.append(f'Yes')
else:
res_check.append(f'No')
return res_check
df_math['Re-test'] = df_math.apply(retest_check, axis=1)
我的代码给我一个错误,它似乎无法识别 'file' 列中的字符串。我该如何解决这个问题?
KeyError: 'file'
您可以使用这种方法:
(df.query('subject == "Math"')
.groupby(['class', 'student'])
.agg({'subject': 'count',
'file': lambda s: 'Yes' if 're_test' in s.values else 'No',
})
.rename(columns={'subject': 'Math (Count)', 'file': 'Re-test'})
)
输出:
Math (Count) Re-test
class student
A John 1 Yes
Mary 1 No
Scott 1 No
B Jack 1 Yes
James 1 No
Mina 1 No
我正在创建一个新专栏,该专栏的依据是学生是否曾经根据 'file' 专栏重新测试过某个科目:
这是行数据:
这就是我想要实现的方式:
这是我的代码:
import pandas as pd
df = pd.DataFrame(columns=['file', 'class', 'student', 'subject', 'scores'],
data=[['re_test', 'A', 'John', 'Math', 60],
['first_test', 'A', 'Scott', 'Math', 75],
['first_test', 'A', 'Mary', 'Math', 80],
['re_test', 'B', 'Jack', 'Math', 70],
['first_test', 'B', 'Mina', 'Math', 75],
['first_test', 'B', 'James', 'Math', 95]])
df_math= df.pivot_table(index= ['class', 'student', 'file'],
values=['subject'], aggfunc=['count'], fill_value = 0)
def retest_check(res):
res_check = []
if 're' in res['file']:
res_check.append(f'Yes')
else:
res_check.append(f'No')
return res_check
df_math['Re-test'] = df_math.apply(retest_check, axis=1)
我的代码给我一个错误,它似乎无法识别 'file' 列中的字符串。我该如何解决这个问题?
KeyError: 'file'
您可以使用这种方法:
(df.query('subject == "Math"')
.groupby(['class', 'student'])
.agg({'subject': 'count',
'file': lambda s: 'Yes' if 're_test' in s.values else 'No',
})
.rename(columns={'subject': 'Math (Count)', 'file': 'Re-test'})
)
输出:
Math (Count) Re-test
class student
A John 1 Yes
Mary 1 No
Scott 1 No
B Jack 1 Yes
James 1 No
Mina 1 No