怎样在dataframe加一列数据
时间: 2024-04-17 17:25:36 浏览: 102
要在DataFrame中添加一列数据,可以通过为DataFrame对象分配一个列表、数组或Series来实现。以下是几种常见的方法:
方法一:使用直接赋值的方式添加列
```python
import pandas as pd
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})
df['C'] = [7, 8, 9]
print(df)
```
输出结果:
```
A B C
0 1 4 7
1 2 5 8
2 3 6 9
```
方法二:使用assign()方法添加列
```python
import pandas as pd
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})
df = df.assign(C=[7, 8, 9])
print(df)
```
输出结果:
```
A B C
0 1 4 7
1 2 5 8
2 3 6 9
```
方法三:使用insert()方法在指定位置添加列
```python
import pandas as pd
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})
df.insert(2, 'C', [7, 8, 9])
print(df)
```
输出结果:
```
A B C
0 1 4 7
1 2 5 8
2 3 6 9
```
这些方法中,都会在DataFrame中添加一列名为'C'的数据列,并提供相应的值。你可以根据需要选择适合的方法来添加数据列。
阅读全文
相关推荐


















