gpt4 book ai didi

python - 有条件地替换 Pandas 数据框中的空白值

转载 作者:行者123 更新时间:2023-11-28 18:19:27 24 4
gpt4 key购买 nike

我有一个数据框,其中有一个稀疏填充的列。大多数值是空白的;唯一的其他值是“买入”和“卖出”。如果最后一个非空白值是“买入”,我想用“多头”替换空白值;如果最后一个非空白值是“卖出”,我想用“空头”替换空白值。我可以在一个循环中很容易地做到这一点,但我想知道是否有一种非循环的方式来完成这个?

最佳答案

您可以使用 fillnacombine_first用于将助手 df 创建的 None 替换为 replaceffill(fillna 方法 ffill - 前向填充 NaNNone):

np.random.seed(12)
df = pd.DataFrame({'A':np.random.choice(['Buy','Sell', None], 10, p=(.2,.2,.6)),
'B':np.random.choice(['Buy','Sell', None], 10, p=(.2,.2,.6)),
'C':np.random.choice(['Buy','Sell', None], 10, p=(.2,.2,.6))})

print (df)

A B C
0 Buy Sell None
1 None None Buy
2 Sell None Buy
3 None None Buy
4 Buy Buy Sell
5 None None None
6 None None None
7 Buy None None
8 None None Sell
9 Buy Buy None

df = df.fillna(df.replace({'Sell':'short', 'Buy':'long'}).ffill())
#alternative solution
#df = df.combine_first(df.replace({'Sell':'short', 'Buy':'long'}).ffill())
print (df)
A B C
0 Buy Sell None
1 long short Buy
2 Sell short Buy
3 short short Buy
4 Buy Buy Sell
5 long long short
6 long long short
7 Buy long short
8 long long Sell
9 Buy Buy short

解释:

print (df.replace({'Sell':'short', 'Buy':'long'}))
A B C
0 long short None
1 None None long
2 short None long
3 None None long
4 long long short
5 None None None
6 None None None
7 long None None
8 None None short
9 long long None

print (df.replace({'Sell':'short', 'Buy':'long'}).ffill())
A B C
0 long short None
1 long short long
2 short short long
3 short short long
4 long long short
5 long long short
6 long long short
7 long long short
8 long long short
9 long long short

关于python - 有条件地替换 Pandas 数据框中的空白值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46144511/

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