我使用下面的代码针对多种类型计算了changbtwread列。
for v in df['Type'].unique():
df[f'Changebetweenreadings_{v}'] = df.loc[df['Type'].eq(v), 'Last'].diff()
给予
Type Last changbtwread_ada changbtwread_btc changbtwread_eur
0 ada 3071.56 NaN NaN NaN
1 ada 3097.82 26.26 NaN NaN
2 btc 1000.00 NaN NaN NaN
3 ada 2000.00 -1097.82 NaN NaN
4 btc 3000.00 NaN 2000.0 NaN
5 eur 1000.00 NaN NaN NaN
6 eur 1500.00 NaN NaN 500.0
现在,我需要基于这些changebtw列来计算方向列。
我的输出应该像
Type change_dir_ada change_dir_btc change_dir_eur
ada Nut
ada Pos
btc Nut
ada Neg
btc Nut
eur
eur Pos
我尝试过的快速修复方法是使用此代码。
df.loc[df.Changebetweenreadings_btceur > 0, 'ChangeDirection_btceur'] = 'Pos'
df.loc[df.Changebetweenreadings_btceur < 0, 'ChangeDirection_btceur'] = 'Neg'
df.loc[df.Changebetweenreadings_btceur == 0, 'ChangeDirection_btceur'] = 'Nut'
df.loc[df.Changebetweenreadings_adabtc > 0, 'ChangeDirection_adabtc'] = 'Pos'
df.loc[df.Changebetweenreadings_adabtc < 0, 'ChangeDirection_adabtc'] = 'Neg'
df.loc[df.Changebetweenreadings_adabtc == 0, 'ChangeDirection_adabtc'] = 'Nut'
但是我这是很多代码,我认为它不是动态的方式。 我希望这样。
for v in df['Type'].unique():
df[f'Changebetweenreadings_{v}'] #--> Do this calculation above.
不适用于这些值
change type dir_ada dir_btc
-3637.31 ada
-4E-08 ada Neg
-3637.31 ada Nut
3637.8 btc Nut
它代替Pos进行随机映射。
答案 0 :(得分:0)
我相信您需要:
vals = ['Pos','Neg', 'Nut']
for v in df['Type'].unique():
df[f'change_dir_{v}'] = df.loc[df['Type'].eq(v), 'Last'].diff()
df[f'change_dir_{v}'] = np.select([df[f'change_dir_{v}'] > 0,
df[f'change_dir_{v}'] < 0,
df[f'change_dir_{v}']== 0], vals, '')
print (df)
Type Last change_dir_ada change_dir_btc change_dir_eur
0 ada 3071.56
1 ada 3097.80 Pos
2 btc 1000.00
3 ada 2000.00 Neg
4 btc 3000.00 Pos
5 eur 1000.00
6 eur 1500.00 Pos