df.insert()插入1列

发布时间 2023-08-21 16:05:25作者: Oops!#

pandas.DataFrame.insert

DataFrame.insert(self, loc, column, value, allow_dupicates=False)

功能:Insert column into DataFrame at specified location

参数详解:
注意:进行insert之后,会修改原数据,且不能用于赋值操作。

  • loc: int # 使用整型数据,是列数据的插入的位置,必须是0到Len(columns)之间的数
  • column: string, number, or hashable object # 类型可以字符串、数字或者object。表示列的标签名
  • value: int, Series, or array-like # 整数、Series或者数组型数据。是插入列的值
  • allow_duplicates: bool, optional # 布尔型数据, 可选参数。如果某个列名在dataframe中已经存在,将allow_duplicates置为true才可以将同样的列名插入

示例

1. 原始数据

import pandas as pd
import numpy as np

df = pd.DataFrame(np.arange(12).reshape(4, 3), columns=['a', 'b', 'c'])
df

output:

 abc
0 0 1 2
1 3 4 5
2 6 7 8
3 9 10 11

2. 插入一列

不能进行赋值,且插入后修改原始数据

df.insert(0, 'd', 2)
df

output:

 dabc
0 2 0 1 2
1 2 3 4 5
2 2 6 7 8
3 2 9 10 11

3. 插入相同列名

# 插入列名”c”,报错,因为原来就有这个列名

df.insert(2, 'c', np.ones(4))

output:

---------------------------------------------------------------------------

ValueError                                Traceback (most recent call last)

~\AppData\Local\Temp\ipykernel_2076\284648989.py in <module>
      1 # 插入列名”c”,报错,因为原来就有这个列名
      2 
----> 3 df.insert(2, 'c', np.ones(4))


D:\anaconda3\lib\site-packages\pandas\core\frame.py in insert(self, loc, column, value, allow_duplicates)
   4441         if not allow_duplicates and column in self.columns:
   4442             # Should this be a different kind of error??
-> 4443             raise ValueError(f"cannot insert {column}, already exists")
   4444         if not isinstance(loc, int):
   4445             raise TypeError("loc must be int")


ValueError: cannot insert c, already exists
  • allow_duplitcats设置为True
# 将allow_duplicates设置为True就可以
df.insert(2, 'c', np.ones(4), allow_duplicates=True)
df
 dacbc
0 2 0 1.0 1 2
1 2 3 1.0 4 5
2 2 6 1.0 7 8
3 2 9 1.0 10 11

 

 

import pandas as pd
import openpyxl



df = pd.read_excel("./2123.xlsx", sheet_name="云服务器 ECS")

AppName_column = df['名称'].str.split('-',expand=True)[0]


df.insert(0,'应用名称',AppName_column)


df.to_excel('./temp.xlsx',index=False)