pandas insert
时间: 2023-08-02 12:11:10 浏览: 74
insert into
Pandas provides the `insert()` function to insert a column into a DataFrame at a specific position. The syntax for `insert()` is as follows:
```python
DataFrame.insert(loc, column, value, allow_duplicates=False)
```
- `loc`: The integer location where the new column will be inserted.
- `column`: The name of the new column.
- `value`: The value to be inserted into the new column.
- `allow_duplicates`: (optional) If set to True, allows inserting a column with a name that already exists in the DataFrame.
Here's an example usage:
```python
import pandas as pd
data = {'Name': ['John', 'Emma', 'Mike'],
'Age': [28, 32, 45]}
df = pd.DataFrame(data)
df.insert(1, 'City', ['London', 'New York', 'Paris'])
print(df)
```
This will insert a new column named 'City' at position 1 in the DataFrame. The resulting DataFrame will look like this:
```
Name City Age
0 John London 28
1 Emma New York 32
2 Mike Paris 45
```
Note that the existing columns will be shifted to the right to accommodate the newly inserted column.
阅读全文