首页 > 解决方案 > 是否可以在 DataFrame 中使用 if 语句在同一时间(只需 1 步)更改 2 列?

问题描述

我在 python 上使用了一些 DataFrame,我遇到了一种情况,我必须在相同的 if 条件下同时更改 2 列。我解决了我的问题,但我并没有只使用一个 if 条件。

我试图搜索有关该内容的内容,但仅在 if 条件具有 2 列或更多列时才发现,而不是在满足条件时才发现。

假设我们有:

data.head()

    Foo
1     a
2     a
3     b
4     b
5     b

如果data['Foo'] == a, 我们做data['Foo'] = cdata['Bar'] = 10, 否则data['Bar'] = 0. 所以,预期的输出是:

data.head()

    Foo  Bar 
1     c   10 
2     c   10
3     b    0
4     b    0
5     b    0

我用两次解决了这个问题np.where()(所以,我验证了 2 个条件)。我必须使用apply()吗?

我想要类似的东西:

if data['Foo'] == a:
   data['Foo'] = c
   data['Bar'] = 10
else:
   data['Bar'] = 0

请注意,它只验证了一次条件。另外,这只是出于好奇:),因为我已经解决了我的问题。

标签: pythonpandasif-statement

解决方案


关闭,您需要的是使用numpy.where

arr = np.where((data['Foo'] == 'a').values[:, None], ['c', 10], ['b', 0])
print (arr)
[['c' '10']
 ['c' '10']
 ['b' '0']
 ['b' '0']
 ['b' '0']]

但是 - 所有值都被转换为字符串,并且也Foo被设置为b。如果在所有列中设置所有数字或所有字符串值,则可能的用例。

data[['Foo','Bar']] = pd.DataFrame(arr, index=data.index)
print (data)
  Foo Bar
1   c  10
2   c  10
3   b   0
4   b   0
5   b   0

仅关闭 pandas 解决方案:

data = data.assign(Bar = 0)
data.loc[data['Foo'] == 'a', ['Foo', 'Bar']] = ['c', 10] 

推荐阅读