本文介紹了在 DataFrame 的開頭(最左端)插入一列的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我有 30 列的數據框,想添加一個新列開始.
I have dataframe with 30 columns and want to add one new column to start.
推薦答案
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
+ 分配
先reindex,然后assign會記住原列的位置.
DataFrame.reindex
+ assign
Reindex first, then assign will remember the position of the original column.
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
這篇關于在 DataFrame 的開頭(最左端)插入一列的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!