【问题标题】:How add multiple columns with a condition Using np.where()如何使用条件添加多个列使用 np.where()
【发布时间】:2021-09-01 17:04:01
【问题描述】:

我知道如何使用 np.where() 以 1 个条件添加一列:

import pandas as pd
import numpy as np
df=pd.read_csv(file,nrows=5)
df['new_col1']= np.where(df['col1'] < '100', 1,2)
df.head()

输出:

   col1  col2  new_col1
0     1     3    1
1     2     4    1

如果我想按相同条件添加 2 列怎么办:

df['new_col1'],df['new_col2']= np.where(df['col1'] < '100', (1,2),(3,4))

我想添加new_col1和new_col2,结果是(1,2),(3,4)

当我尝试这段代码时,我收到了:

ValueError: too many values to unpack (expected 2)

输出应该是:

   col1  col2  new_col1 new_col2
0     1     3    1       3
1     2     4    1       3

【问题讨论】:

  • np.where 返回一个值。您能否详细说明您希望如何生成两个要添加的值?
  • 感谢您的回复,如果我想按1个条件添加2列,我还需要使用什么?
  • 我不明白您所说的“按 1 个条件添加 2 列”是什么意思。你能举个例子吗?
  • df['column1'],df['column2']= np.where(df['contract'] > '0L000099', 1,2)
  • 在上面的np.where定义column1后使用df['column2'] = df['column1'] ?

标签: python python-3.x pandas dataframe numpy


【解决方案1】:

你可以多次使用条件:

mask = df['contract'] > '0L000099'
df['column1'] = np.where(mask, 1, 2)
df['column2'] = np.where(mask, 3, 4)

甚至反转条件:

df['column2'] = np.where(~mask, 1, 2)

由于您的问题已更新,因此这里是更新后的答案,但我不确定这是否真的有用:

import pandas as pd
df = pd.DataFrame({'test':range(0,10)})
mask  = df['test'] > 3
m_len = len(mask)

df['column1'], df['column2'] = np.where([mask, mask], [[1]*m_len, [3]*m_len], [[2]*m_len, [4]*m_len])

   test  column1  column2
0     0        2        4
1     1        2        4
2     2        2        4
3     3        2        4
4     4        1        3
5     5        1        3
6     6        1        3
7     7        1        3
8     8        1        3
9     9        1        3

【讨论】:

  • 谢谢你的回答,你能给我解释一下这条线是什么意思吗:[1]*m_len, [3]*m_len], [[2]*m_len, [4 ]*m_len]
  • @William,ofc,如果您想查找它,它是一个称为广播的 numpy 特定的东西。由于矢量化,numpy 本质上是非常有效的,因为这个 numpy 期望某些格式使用它。在这种情况下,条件中的每个布尔值都需要一个 1。因此我们必须重复这个值,我们可以通过乘以条件序列的长度来做到这一点。希望这是有道理的。
  • 你好朋友你能帮我解决这个问题吗?stackoverflow.com/questions/68476193/…
  • @William,嘿,William,在你的问题下看到我的回答。让我知道进展如何。编码愉快!
猜你喜欢
  • 2016-08-04
  • 2021-09-17
  • 2018-03-21
  • 2021-07-16
  • 2022-06-13
  • 1970-01-01
  • 1970-01-01
  • 2020-04-02
  • 1970-01-01
相关资源
最近更新 更多