我试图弄清楚如何同时添加多个列的熊猫与熊猫。我希望在一个步骤中做到这一点,而不是重复多个步骤。

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...

当前回答

你可以对列名和值的字典使用赋值。

In [1069]: df.assign(**{'col_new_1': np.nan, 'col2_new_2': 'dogs', 'col3_new_3': 3})
Out[1069]:
   col_1  col_2 col2_new_2  col3_new_3  col_new_1
0      0      4       dogs           3        NaN
1      1      5       dogs           3        NaN
2      2      6       dogs           3        NaN
3      3      7       dogs           3        NaN

其他回答

你可以使用元组解包:

df = pd.DataFrame({'col1': [1, 2], 'col2': [3, 4]})

df['col3'], df['col4'] = 'a', 10

结果:

   col1  col2 col3  col4
0     1     3    a    10
1     2     4    a    10

你可以对列名和值的字典使用赋值。

In [1069]: df.assign(**{'col_new_1': np.nan, 'col2_new_2': 'dogs', 'col3_new_3': 3})
Out[1069]:
   col_1  col_2 col2_new_2  col3_new_3  col_new_1
0      0      4       dogs           3        NaN
1      1      5       dogs           3        NaN
2      2      6       dogs           3        NaN
3      3      7       dogs           3        NaN

只是想指出@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
df = pd.DataFrame({
 'col_1': [0, 1, 2, 3], 
 'col_2': [4, 5, 6, 7]
 })
df['col_3'],  df['col_4'] =  [df.col_1]*2

>> df
col_1   col_2   col_3   col_4
0      4       0       0
1      5       1       1
2      6       2       2
3      7       3       3

我不习惯使用“Index”等等。可以如下所示

df.columns
Index(['A123', 'B123'], dtype='object')

df=pd.concat([df,pd.DataFrame(columns=list('CDE'))])

df.rename(columns={
    'C':'C123',
    'D':'D123',
    'E':'E123'
},inplace=True)


df.columns
Index(['A123', 'B123', 'C123', 'D123', 'E123'], dtype='object')