我需要遍历此数据框的'Grade'
列,并将"1"
,"2"
或"K"
的条目替换为"1/2"
和{{1 }}或"3"
与"4"
"3/4"
这是DF:
for i in kids_df:
if kids_df['G'] == 1 or 2:
kids_df['G'] = kids_df['Grade'].replace('1/2')
我正在寻找的结果:
Name M/F Grade Size Notes
0 Peter Parker M 2 YM Baughman
1 Tony Stark M 1 YL Baughman
2 Steve Rogers M K YM Baughman
3 Donald Blake M 2 YM Baughman
4 Bruce Banner M 3 YM Baughman
答案 0 :(得分:1)
尝试使用np.where
:
df['Grade'] = np.where(df['Grade'].isin(['1', '2', 'K']), '1/2', '3/4')
print(df)
或使用双str.replace
:
df['Grade'] = df['Grade'].str.replace('1|2|K', '1/2').str.replace('3|4', '3/4')
print(df)
或在字典中使用replace
:
df['Grade'] = df['Grade'].replace({'1|2|K': '1/2', '3|4': '3/4'}, regex=True)
print(df)
它们全部输出:
Name M/F Grade Size Notes
0 Peter Parker M 1/2 YM Baughman
1 Tony Stark M 1/2 YL Baughman
2 Steve Rogers M 1/2 YM Baughman
3 Donald Blake M 1/2 YM Baughman
4 Bruce Banner M 3/4 YM Baughman
答案 1 :(得分:0)
我们可以做replace
kids_df['G']=kids_df['G'].replace({1:'1/2',2:'1/2',3:'3/4',4:'3/4'})