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

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

当前回答

在编写Pandas时,我的目标是编写可以链接的高效可读代码。我不会在这里解释为什么我这么喜欢链接,我在我的书《Effective Pandas》中对此进行了阐述。

我经常希望以简洁的方式添加新列,这也允许我进行链接。我的一般规则是使用.assign方法更新或创建列。

为了回答你的问题,我将使用以下代码:

(df
 .assign(column_new_1=np.nan,
         column_new_2='dogs',
         column_new_3=3
        )
)

再深入一点。我经常有一个数据框架,其中有我想要添加到我的数据框架的新列。让我们假设它看起来像…一个你想要的三列的数据框架:

df2 = pd.DataFrame({'column_new_1': np.nan,
                    'column_new_2': 'dogs',
                    'column_new_3': 3},
                   index=df.index
                  )

在这种情况下,我将编写以下代码:

(df
 .assign(**df2)
)

其他回答

如果您只是想添加空的新列,重新索引将完成这项工作

df
   col_1  col_2
0      0      4
1      1      5
2      2      6
3      3      7

df.reindex(list(df)+['column_new_1', 'column_new_2','column_new_3'], axis=1)
   col_1  col_2  column_new_1  column_new_2  column_new_3
0      0      4           NaN           NaN           NaN
1      1      5           NaN           NaN           NaN
2      2      6           NaN           NaN           NaN
3      3      7           NaN           NaN           NaN

完整的代码示例

import numpy as np
import pandas as pd

df = {'col_1': [0, 1, 2, 3],
        'col_2': [4, 5, 6, 7]}
df = pd.DataFrame(df)
print('df',df, sep='\n')
print()
df=df.reindex(list(df)+['column_new_1', 'column_new_2','column_new_3'], axis=1)
print('''df.reindex(list(df)+['column_new_1', 'column_new_2','column_new_3'], axis=1)''',df, sep='\n')

否则就用赋值来赋0

你可以使用元组解包:

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

我不习惯使用“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')

使用列表理解,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)

使用.assign()映射字典:

这是在处理多个列时用值分配新列的最具可读性和最动态的方式。

import pandas as pd
import numpy as np

new_cols = ["column_new_1", "column_new_2", "column_new_3"]
new_vals = [np.nan, "dogs", 3]
# Map new columns as keys and new values as values
col_val_mapping = dict(zip(new_cols, new_vals))
# Unpack new column/new value pairs and assign them to the data frame
df = df.assign(**col_val_mapping)

如果你只是想把新列的值初始化为空,因为你不知道这些值会是什么,或者你有很多新列。

import pandas as pd
import numpy as np

new_cols = ["column_new_1", "column_new_2", "column_new_3"]
new_vals = [None for item in new_cols]
# Map new columns as keys and new values as values
col_val_mapping = dict(zip(new_cols, new_vals))
# Unpack new column/new value pairs and assign them to the data frame
df = df.assign(**col_val_mapping)