python - 如何根据其他两列中的值设置第三列中的值

标签 python

我有一个如下所示的数据框。

Key|Direction
:--|-------: 
x  | Sell
x  | Buy
x  | BUY
y  | Sell
y  | Sell
y  | Sell
Z  | Buy
Z  | Buy
a  | Buy
a  | Sell

我想要做的是创建第三列,对于所有相同的键,如果该键有买入和卖出,则第三列会说"is"。如果不是,它只是说不。我正在使用 groupby,但我发现很难将值重新分配回数据框中。这就是我希望最后一栏的样子

Key|Direction |Cross
:--|-------   |------
x  | Sell     | yes
x  | Buy      | yes
x  | BUY      | yes
y  | Sell     | no
y  | Sell     | no
y  | Sell     | no
Z  | Buy      | no 
Z  | Buy      | no
a  | Buy      | yes
a  | Sell     | yes

最佳答案

您可以使用groupby + transform比较 set 和最后一个 map通过字典:

d = {True:'yes', False:'no'}
df['Cross'] = df.groupby('Key')['Direction'] \
                .transform(lambda x: set(x) == set(['Buy','Sell'])).map(d)
print (df)
  Key Direction Cross
0   x      Sell   yes
1   x       Buy   yes
2   x       Buy   yes
3   y      Sell    no
4   y      Sell    no
5   y      Sell    no
6   Z       Buy    no
7   Z       Buy    no
8   a       Buy   yes
9   a      Sell   yes

另一个解决方案,创建系列mapSeries 作为新列,与 eq 进行比较(==) 和 dict 的最后一张 map :

d = {True:'yes', False:'no'}
s = df.groupby('Key')['Direction'].apply(set)
df['Cross'] = df['Key'].map(s).eq(set(['Buy','Sell'])).map(d)
print (df)
  Key Direction Cross
0   x      Sell   yes
1   x       Buy   yes
2   x       Buy   yes
3   y      Sell    no
4   y      Sell    no
5   y      Sell    no
6   Z       Buy    no
7   Z       Buy    no
8   a       Buy   yes
9   a      Sell   yes
<小时/>

numpy.where 类似的解决方案:

s = df.groupby('Key')['Direction'].apply(set)
df['Cross'] = np.where(df['Key'].map(s).eq(set(['Buy','Sell'])), 'yes', 'no')
print (df)
  Key Direction Cross
0   x      Sell   yes
1   x       Buy   yes
2   x       Buy   yes
3   y      Sell    no
4   y      Sell    no
5   y      Sell    no
6   Z       Buy    no
7   Z       Buy    no
8   a       Buy   yes
9   a      Sell   yes

关于python - 如何根据其他两列中的值设置第三列中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44845416/

相关文章:

python - 动态 Canvas 控制

python - 将列表切片追加回原始列表是否只是复制地址?

python - 字符串系列到数组

python - 交叉熵损失突然增加到无穷大

python - 为什么这不起作用(sqlite,python)

python - 哪个版本的 TensorFlow.js 与在 TensorFlow 1.12.0 (Python) 中训练的模型兼容?

python - 如何在所有测试和拆卸完成后调用一次设置

python - 如何设置django开发服务器

python - 如何构建Python装饰函数以使其更易于维护?

python - Django:ModelChoiceField 和 django.setup()