如何在 Pandas 中的特定列索引处插入一列?
- 2025-02-28 08:23:00
- admin 原创
- 75
问题描述:
我可以在 Pandas 中的特定列索引处插入一列吗?
import pandas as pd
df = pd.DataFrame({'l':['a','b','c','d'], 'v':[1,2,1,2]})
df['n'] = 0
这会将列设置n
为的最后一列df
,但没有办法告诉df
将其放在n
开头吗?
解决方案 1:
查看文档:http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.insert.html
使用 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
解决方案 2:
如果您希望所有行都有一个值:
df.insert(0,'name_of_column','')
df['name_of_column'] = value
编辑:
您还可以:
df.insert(0,'name_of_column',value)
解决方案 3:
df.insert(loc, column_name, value)
如果没有其他同名列,此方法将有效。如果数据框中已存在具有您提供的名称的列,则会引发 ValueError。
allow_duplicates
您可以传递带有值的可选参数True
来创建具有已存在列名的新列。
以下是一个例子:
>>> df = pd.DataFrame({'b': [1, 2], 'c': [3,4]})
>>> df
b c
0 1 3
1 2 4
>>> df.insert(0, 'a', -1)
>>> df
a b c
0 -1 1 3
1 -1 2 4
>>> df.insert(0, 'a', -2)
Traceback (most recent call last):
File "", line 1, in
File "C:Python39libsite-packagespandascorerame.py", line 3760, in insert
self._mgr.insert(loc, column, value, allow_duplicates=allow_duplicates)
File "C:Python39libsite-packagespandascoreinternalsmanagers.py", line 1191, in insert
raise ValueError(f"cannot insert {item}, already exists")
ValueError: cannot insert a, already exists
>>> df.insert(0, 'a', -2, allow_duplicates = True)
>>> df
a a b c
0 -2 -1 1 3
1 -2 -1 2 4
解决方案 4:
您可以尝试将列提取为列表,根据需要对其进行调整,然后重新索引数据框:
>>> 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
编辑:这可以在一行中完成;但是,这看起来有点丑陋。也许可能会出现一些更清晰的提议...
>>> 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
解决方案 5:
通用的 4 行程序
每当您想要创建一个新列并插入到特定位置时,您都可以使用以下 4 行例程loc
。
df['new_column'] = ... #new column's definition
col = df.columns.tolist()
col.insert(loc, col.pop()) #loc is the column's index you want to insert into
df = df[col]
在您的示例中,它很简单:
df['n'] = 0
col = df.columns.tolist()
col.insert(0, col.pop())
df = df[col]
解决方案 6:
这是一个非常简单的答案(只有一行)。
您可以在将“n”列添加到 df 后执行此操作,如下所示。
import pandas as pd
df = pd.DataFrame({'l':['a','b','c','d'], 'v':[1,2,1,2]})
df['n'] = 0
df
l v n
0 a 1 0
1 b 2 0
2 c 1 0
3 d 2 0
# here you can add the below code and it should work.
df = df[list('nlv')]
df
n l v
0 0 a 1
1 0 b 2
2 0 c 1
3 0 d 2
However, if you have words in your columns names instead of letters. It should include two brackets around your column names.
import pandas as pd
df = pd.DataFrame({'Upper':['a','b','c','d'], 'Lower':[1,2,1,2]})
df['Net'] = 0
df['Mid'] = 2
df['Zsore'] = 2
df
Upper Lower Net Mid Zsore
0 a 1 0 2 2
1 b 2 0 2 2
2 c 1 0 2 2
3 d 2 0 2 2
# here you can add below line and it should work
df = df[list(('Mid','Upper', 'Lower', 'Net','Zsore'))]
df
Mid Upper Lower Net Zsore
0 2 a 1 0 2
1 2 b 2 0 2
2 2 c 1 0 2
3 2 d 2 0 2
相关推荐
热门文章
项目管理软件有哪些?
热门标签
曾咪二维码
扫码咨询,免费领取项目管理大礼包!
云禅道AD