Python 如何在 Pandas 的特定列索引处插入一列?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18674064/
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 11:24:38  来源:igfitidea点击:

how do I insert a column at a specific column index in pandas?

pythonindexingpandas

提问by HappyPy

Can I insert a column at a specific column index in pandas?

我可以在 Pandas 的特定列索引处插入一列吗?

import pandas as pd
df = pd.DataFrame({'l':['a','b','c','d'], 'v':[1,2,1,2]})
df['n'] = 0

This will put column nas the last column of df, but isn't there a way to tell dfto put nat the beginning?

这会将列n作为 的最后一列df,但是没有办法告诉df将放在n开头吗?

采纳答案by Jeff

see docs: http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.insert.html

见文档:http: //pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.insert.html

using loc = 0 will insert at the beginning

使用 loc = 0 将在开头插入

df.insert(loc, column, 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

回答by Nic

You could try to extract columns as list, massage this as you want, and reindex your dataframe:

您可以尝试将列提取为列表,根据需要对其进行按摩,然后重新索引您的数据框:

>>> cols = df.columns.tolist()
>>> cols = [cols[-1]]+cols[:-1] # or whatever change you need
>>> df.reindex(columns=cols)

   n  l  v
0  0  a  1
1  0  b  2
2  0  c  1
3  0  d  2

EDIT: this can be done in one line ; however, this looks a bit ugly. Maybe some cleaner proposal may come...

编辑:这可以在一行中完成;然而,这看起来有点难看。也许一些更清洁的建议可能会出现......

>>> df.reindex(columns=['n']+df.columns[:-1].tolist())

   n  l  v
0  0  a  1
1  0  b  2
2  0  c  1
3  0  d  2

回答by Hugo Vares

If you want a single value for all rows:

如果您想要所有行的单个值:

df.insert(0,'name_of_column','')
df['name_of_column'] = value

Edit:

编辑:

You can also:

你也可以:

df.insert(0,'name_of_column',value)