python df1.insert
时间: 2023-10-29 19:05:56 浏览: 47
df1.insert() is a method in pandas library of Python used to insert a column into a DataFrame at a specified position. It has the following syntax:
```python
df1.insert(loc, column, value, allow_duplicates=False)
```
- loc: The position at which the new column should be inserted.
- column: The name of the new column.
- value: The value to be inserted in the new column.
- allow_duplicates (optional): Whether to allow duplicate column names. By default, it is set to False.
For example, let's say we have a DataFrame `df1`:
```python
import pandas as pd
data = {'Name': ['John', 'Emma', 'Alex'],
'Age': [28, 25, 32]}
df1 = pd.DataFrame(data)
print(df1)
```
Output:
```
Name Age
0 John 28
1 Emma 25
2 Alex 32
```
To insert a new column named "Salary" at position 1 with values [5000, 6000, 7000], we can use the `df1.insert()` method:
```python
df1.insert(1, "Salary", [5000, 6000, 7000])
print(df1)
```
Output:
```
Name Salary Age
0 John 5000 28
1 Emma 6000 25
2 Alex 7000 32
```
The new column "Salary" is inserted at position 1, shifting the existing columns to the right.
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)