gpt4 book ai didi

Python Pandas .loc 一次更新 2 列

转载 作者:行者123 更新时间:2023-12-01 09:20:21 24 4
gpt4 key购买 nike

我在 pandas 中遇到问题,我对数据进行了许多更改。但最终我不知道是哪个变化导致了该列中值的最终状态。

例如,我像这样改变音量。但我运行了很多这样的检查:

# Last check 
for i in range(5):
df_gp.tail(1).loc[ (df_gp['volume']<df_gp['volume'].shift(1)) | (df_gp['volume']<0.4),['new_volume'] ] = df_gp['new_volume']*1.1

如果满足条件,我不仅要更新“new_volume”列,还要更新“commentary”列。

是否可以将其添加到某处,以便我的“评论”与“new_volume”同时更新?

谢谢!

最佳答案

是的,可以通过assign ,但在我看来可读性较差,更好的是通过变量中缓存的 bool 掩码分别更新每列:

df_gp = pd.DataFrame({'volume':[.1,.3,.5,.7,.1,.7],
'new_volume':[5,3,6,9,2,4],
'commentary':list('aaabbb')})

print (df_gp)
volume new_volume commentary
0 0.1 5 a
1 0.3 3 a
2 0.5 6 a
3 0.7 9 b
4 0.1 2 b
5 0.7 4 b
<小时/>
#create boolean mask and assign to variable for reuse
m = (df_gp['volume']<df_gp['volume'].shift(1)) | (df_gp['volume']<0.4)

#change columns by assign by condition and assign back only filtered columns
c = ['commentary','new_volume']
df_gp.loc[m, c] = df_gp.loc[m, c].assign(new_volume=df_gp['new_volume']*1.1
commentary='updated')
print (df_gp)
volume new_volume commentary
0 0.1 5.5 updated
1 0.3 3.3 updated
2 0.5 6.0 a
3 0.7 9.0 b
4 0.1 2.2 updated
5 0.7 4.0 b
<小时/>
#multiple filtered column by scalar
df_gp.loc[m, 'new_volume'] *= 1.1
#append new value to filtered column
df_gp.loc[m, 'commentary'] = 'updated'
print (df_gp)
volume new_volume commentary
0 0.1 5.5 updated
1 0.3 3.3 updated
2 0.5 6.0 a
3 0.7 9.0 b
4 0.1 2.2 updated
5 0.7 4.0 b

关于Python Pandas .loc 一次更新 2 列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50835902/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com