我试图弄清楚如何同时添加多个列的熊猫与熊猫。我希望在一个步骤中做到这一点,而不是重复多个步骤。
import pandas as pd
df = {'col_1': [0, 1, 2, 3],
'col_2': [4, 5, 6, 7]}
df = pd.DataFrame(df)
df[[ 'column_new_1', 'column_new_2','column_new_3']] = [np.nan, 'dogs',3] # I thought this would work here...
使用列表理解,pd。DataFrame和pd.concat
pd.concat(
[
df,
pd.DataFrame(
[[np.nan, 'dogs', 3] for _ in range(df.shape[0])],
df.index, ['column_new_1', 'column_new_2','column_new_3']
)
], axis=1)
只是想指出@Matthias Fripp回答中的选项2
(2)我并不一定期望DataFrame以这种方式工作,但它确实如此
df[[‘column_new_1’,‘column_new_2’,‘column_new_3]] = pd.DataFrame ([[np。Nan, 'dogs', 3]], index=df.index)
熊猫自己的文档中已经有记录了吗
http://pandas.pydata.org/pandas-docs/stable/indexing.html#basics
您可以将列列表传递给[]以按此顺序选择列。
如果数据帧中不包含列,则会引发异常。
也可以通过这种方式设置多个列。
您可能会发现这对于将转换(就地)应用到列的子集很有用。
你可以实例化一个字典的值,如果你想为每一列不同的值&你不介意在行之前创建一个字典。
>>> import pandas as pd
>>> import numpy as np
>>> df = pd.DataFrame({
'col_1': [0, 1, 2, 3],
'col_2': [4, 5, 6, 7]
})
>>> df
col_1 col_2
0 0 4
1 1 5
2 2 6
3 3 7
>>> cols = {
'column_new_1':np.nan,
'column_new_2':'dogs',
'column_new_3': 3
}
>>> df[list(cols)] = pd.DataFrame(data={k:[v]*len(df) for k,v in cols.items()})
>>> df
col_1 col_2 column_new_1 column_new_2 column_new_3
0 0 4 NaN dogs 3
1 1 5 NaN dogs 3
2 2 6 NaN dogs 3
3 3 7 NaN dogs 3
不一定比公认的答案更好,但这是另一种尚未列出的方法。