如何在pandas中的特定列索引处插入列? [英] how do I insert a column at a specific column index in pandas?
本文介绍了如何在pandas中的特定列索引处插入列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我可以在pandas中的特定列索引处插入一列吗?
Can I insert a column at a specific column index in pandas?
import pandas as pd
df = pd.DataFrame({'l':['a','b','c','d'], 'v':[1,2,1,2]})
df['n'] = 0
这将列 n
作为 df的最后一列
,但是没有办法告诉 df
在开头放
This will put column n
as the last column of df
, but isn't there a way to tell df
to put n
at the beginning?
推荐答案
参见docs: http://pandas.pydata.org/pandas-docs/stable/dsintro.html#column-selection-addition-deletion
将在开头插入
df.insert(idx, col_name, value)
df = pd.DataFrame({'B': [1, 2, 3], 'C': [4, 5, 6]})
df
Out:
B C
0 1 4
1 2 5
2 3 6
idx = 0
new_col = [7, 8, 9] # can be a list, a Series, an array or a scalar
df.insert(loc=idx, column='A', value=new_col)
df
Out:
A B C
0 7 1 4
1 8 2 5
2 9 3 6
这篇关于如何在pandas中的特定列索引处插入列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文