Python 将多个空列添加到 Pandas DataFrame

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30926670/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 09:10:59  来源:igfitidea点击:

Add multiple empty columns to pandas DataFrame

pythonpandas

提问by Winterflags

This may be a stupid question, but how do I add multiple empty columns to a DataFrame from a list?

这可能是一个愚蠢的问题,但是如何从列表向 DataFrame 添加多个空列?

I can do:

我可以:

df["B"] = None
df["C"] = None
df["D"] = None

But I can't do:

但我不能这样做:

df[["B", "C", "D"]] = None

KeyError: "['B' 'C' 'D'] not in index"

采纳答案by EdChum

I'd concatusing a DataFrame:

我会concat使用数据帧:

In [23]:
df = pd.DataFrame(columns=['A'])
df

Out[23]:
Empty DataFrame
Columns: [A]
Index: []

In [24]:    
pd.concat([df,pd.DataFrame(columns=list('BCD'))])

Out[24]:
Empty DataFrame
Columns: [A, B, C, D]
Index: []

So by passing a list containing your original df, and a new one with the columns you wish to add, this will return a new df with the additional columns.

因此,通过传递一个包含原始 df 的列表和一个包含您希望添加的列的新列表,这将返回一个带有附加列的新 df。



Caveat: See the discussion of performance in the other answersand/or the comment discussions. reindexmay be preferable where performance is critical.

警告:请参阅其他答案和/或评论讨论中的性能讨论。reindex在性能至关重要的情况下可能更可取。

回答by unutbu

You could use df.reindexto add new columns:

您可以使用df.reindex添加新列:

In [18]: df = pd.DataFrame(np.random.randint(10, size=(5,1)), columns=['A'])

In [19]: df
Out[19]: 
   A
0  4
1  7
2  0
3  7
4  6

In [20]: df.reindex(columns=list('ABCD'))
Out[20]: 
   A   B   C   D
0  4 NaN NaN NaN
1  7 NaN NaN NaN
2  0 NaN NaN NaN
3  7 NaN NaN NaN
4  6 NaN NaN NaN

reindexwill return a new DataFrame, with columns appearing in the order they are listed:

reindex将返回一个新的 DataFrame,列按它们列出的顺序出现:

In [31]: df.reindex(columns=list('DCBA'))
Out[31]: 
    D   C   B  A
0 NaN NaN NaN  4
1 NaN NaN NaN  7
2 NaN NaN NaN  0
3 NaN NaN NaN  7
4 NaN NaN NaN  6

The reindexmethod as a fill_valueparameter as well:

reindex方法也作为fill_value参数:

In [22]: df.reindex(columns=list('ABCD'), fill_value=0)
Out[22]: 
   A  B  C  D
0  4  0  0  0
1  7  0  0  0
2  0  0  0  0
3  7  0  0  0
4  6  0  0  0

回答by toto_tico

If you don't want to rewrite the name of the old columns, then you can use reindex:

如果不想重写旧列的名称,则可以使用 reindex:

df.reindex(columns=[*df.columns.tolist(), 'new_column1', 'new_column2'], fill_value=0)


Full example:

完整示例

In [1]: df = pd.DataFrame(np.random.randint(10, size=(3,1)), columns=['A'])

In [1]: df
Out[1]: 
   A
0  4
1  7
2  0

In [2]: df.reindex(columns=[*df.columns.tolist(), 'col1', 'col2'], fill_value=0)
Out[2]: 

   A  col1  col2
0  1     0     0
1  2     0     0


And, if you already have a listwith the column names, :

而且,如果您已经有一个包含列名的列表,则:

In [3]: my_cols_list=['col1','col2']

In [4]: df.reindex(columns=[*df.columns.tolist(), *my_cols_list], fill_value=0)
Out[4]: 
   A  col1  col2
0  1     0     0
1  2     0     0

回答by alexprice

Why not just use loop:

为什么不直接使用循环:

for newcol in ['B','C','D']:
    df[newcol]=0

回答by Oleg O

Just to add to the list of funny ways:

只是添加到有趣的方式列表中:

columns_add = ['a', 'b', 'c']
df = df.assign(**dict(zip(columns_add, [0] * len(columns_add)))