pandas 在 DataFrame 的开头(最左端)插入一列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46307681/
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-09-14 04:29:21 来源:igfitidea点击:
Insert a column at the beginning (leftmost end) of a DataFrame
提问by SPy
I have dataframe with 30 columns and want to add one new column to start.
我有 30 列的数据框,想添加一个新列来开始。
回答by cs95
df = pd.DataFrame({'A': ['x'] * 3, 'B': ['x'] * 3})
df
A B
0 x x
1 x x
2 x x
seq = ['a', 'b', 'c']
# This works in-place.
df.insert(0, 'C', seq)
df
C A B
0 a x x
1 b x x
2 c x x
df = pd.concat([pd.Series(seq, index=df.index, name='C'), df], axis=1)
df
C A B
0 a x x
1 b x x
2 c x x
DataFrame.reindex
+ assign
Reindex first, then assign will remember the position of the original column.
DataFrame.reindex
+assign
首先重新索引,然后分配会记住原始列的位置。
df.reindex(['C', *df.columns], axis=1).assign(C=seq)
C A B
0 a x x
1 b x x
2 c x x