Pandas 循环遍历字典并应用数据帧转换
我有一个数据帧。我想说的是,对于所有以“A”或“C”开头的列,然后将所有行除以列平均值 我不明白为什么我的代码不起作用Pandas 循环遍历字典并应用数据帧转换,pandas,dictionary,Pandas,Dictionary,我有一个数据帧。我想说的是,对于所有以“A”或“C”开头的列,然后将所有行除以列平均值 我不明白为什么我的代码不起作用 dict_trans={'A':'STA' ,'B':'SUB' ,'C':'STA'} for k, v in dict_trans.items(): if df_train.columns.str.startswith(k): transformation=v if transformation='STA
dict_trans={'A':'STA'
,'B':'SUB'
,'C':'STA'}
for k, v in dict_trans.items():
if df_train.columns.str.startswith(k):
transformation=v
if transformation='STA':
df['STA_'+varname]=df[varname]/df.groupby(level=1)[varname].transform('mean')
请按照下面的代码操作。我希望你是在做手术 以某个匹配字符开头并希望创建的某些列 新功能
# Creating a sample data frame :
df=pd.DataFrame({'A_1':range(10),
'A_2':range(10,20),
'B_2':range(21,31),
'C_1':range(32,42)})
columns_required=list(filter(lambda x:(x.startswith('A') or x.startswith('C') ),(df.columns).tolist()))
dict_trans={'A_1':'STA'
,'A_2':'SUB'
,'B_2':'STA',
'C_1':'STA'}
for index,value in dict_trans.items():
if index in columns_required and value=='STA':
df['STA_'+index]=df.loc[:,index]/(df.loc[:,index]).mean()
结果是:
if transformation='STA'应该是if transformation='STA'。在将来,如果你也能发布错误消息,那就太好了。
A_1 A_2 B_2 C_1 STA_A_1 STA_C_1
0 0 10 21 32 0.000000 0.876712
1 1 11 22 33 0.222222 0.904110
2 2 12 23 34 0.444444 0.931507
3 3 13 24 35 0.666667 0.958904
4 4 14 25 36 0.888889 0.986301
5 5 15 26 37 1.111111 1.013699
6 6 16 27 38 1.333333 1.041096
7 7 17 28 39 1.555556 1.068493
8 8 18 29 40 1.777778 1.095890
9 9 19 30 41 2.000000 1.123288