如何根据多个条件替换 2 个数据框列中的值?

时间:2021-03-29 11:57:04

标签: python pandas dataframe

我在 Pandas 数据框中有如下所示的列:

<头>
中性
1 0 1
0 1 0

我希望它看起来像这样:

<头>
中性 混合
0 0 0 1
0 1 0 0

首先,我根据句子既是肯定的又是否定的这一事实创建了名为混合的列。现在,由于我已经有“混合”列,我不需要双重信息,所以我想用 0 替换正列和负列中的值(仅适用于混合情绪句子)。我已经尝试了 np.where 的不同变体,但似乎没有人理解如何根据这 2 列中的条件替换 2 列中的值。 有什么建议么?谢谢:)

2 个答案:

答案 0 :(得分:0)

你的问题有点不清楚。我想你的问题(如果我是对的)是从这个改变:

<头>
正面 中立 否定
1 0 1

对此(因为您有一个名为“混合”的新列):

<头>
正面 中立 否定 混合
0 0 0 1

如果是这种情况,那么代码应该是(为了便于查看,我将表格设为 3 行而不是 1 行):

import pandas as pd

data = {'Positive': [1, 1, 1], 'Neutral': [0, 0, 0], 'Negative': [1, 1, 1]}
df = pd.DataFrame(data)
print(df)
print(\n)
x = (df['Positive'])
x[1] = 0 
print(df)

结果,在第二行“Positive”列中,值从“1”变为“0”。

使用不同的索引,您可以在x[i] = 0处自行调整代码。类似的代码应用于“否定”列。

答案 1 :(得分:0)

您可以分两步完成 - 设置混合列 - 然后将 pos/neg 列设置为 0。

>>> df['Mixed'] = 0
>>> df
   Positive  Neutral  Negative  Mixed
0         1        0         1      0
1         0        1         0      0
>>> rows = (df.Positive == 1) & (df.Negative == 1)
>>> df.loc[rows, 'Mixed'] = 1
>>> df.loc[rows, ['Positive', 'Negative']] = 0
>>> df
   Positive  Neutral  Negative  Mixed
0         0        0         0      1
1         0        1         0      0

你可以使用 df.mask() 如果你想一起做。

>>> df
   Positive  Neutral  Negative  Mixed
0         1        0         1      0
1         0        1         0      0
>>> rows = (df.Positive == 1) & (df.Negative == 1)
>>> df.mask(rows, [0, 0, 0, 1])
   Positive  Neutral  Negative  Mixed
0         0        0         0      1
1         0        1         0      0