加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – 在DataFrame的开头(最左端)插入一个列

发布时间:2020-12-20 12:03:30 所属栏目:Python 来源:网络整理
导读:参见英文答案 how do I insert a column at a specific column index in pandas?????????????????????????????????????2个 我有30列的数据框,并希望添加一个新列开始. 解决方法 DataFrame.insert df = pd.DataFrame({'A': ['x'] * 3,'B': ['x'] * 3})df A B0
参见英文答案 > how do I insert a column at a specific column index in pandas?????????????????????????????????????2个
我有30列的数据框,并希望添加一个新列开始.

解决方法

DataFrame.insert

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

pd.concat

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
首先重新索引,然后分配将记住原始列的位置.

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读