如何基于多个条件替换2个数据帧列中的值?

2024-04-29 12:57:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我在pandas dataframe中有如下列:

^{tb1}$

我希望它看起来像这样:

^{tb2}$

首先,我创建了一个名为mixed的专栏,这个专栏基于这样一个事实:这个句子既有积极的一面,也有消极的一面。现在,因为我已经有了列“mixed”,所以我不需要双重信息,所以我想用0来替换正负列中的值(仅适用于混合情感句子)。我尝试了np的不同变体,但似乎没有人理解如何根据这两列的条件替换这两列中的值。 有什么建议吗?谢谢:)


Tags: 信息dataframepandasnp变体条件事实句子
2条回答

你的问题有点不清楚。我想你的问题(如果我是正确的)是从以下方面改变:

^{tb1}$

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

^{tb2}$

如果是这种情况,那么代码应该是(为了便于查看,我将表设为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)

结果,第二行“正”列中的值从“1”更改为“0”

使用不同的索引,您可以在x[i] = 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
   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

相关问题 更多 >