【发布时间】: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