python中df的添加数据和删除数据的代码
时间: 2023-06-27 17:02:02 浏览: 50
向pandas DataFrame中添加数据的方法有多种,以下是其中两种:
1. 使用`loc`方法添加一行数据:
```python
import pandas as pd
df = pd.DataFrame({'A': [1, 2], 'B': [3, 4]})
new_row = {'A': 5, 'B': 6}
df = df.append(new_row, ignore_index=True)
print(df)
```
输出:
```
A B
0 1 3
1 2 4
2 5 6
```
2. 使用`loc`方法添加一列数据:
```python
df['C'] = [7, 8, 9]
print(df)
```
输出:
```
A B C
0 1 3 7
1 2 4 8
2 5 6 9
```
删除pandas DataFrame中的数据可以使用`drop`方法:
1. 删除一行数据:
```python
df = df.drop(1)
print(df)
```
输出:
```
A B C
0 1 3 7
2 5 6 9
```
2. 删除一列数据:
```python
df = df.drop('C', axis=1)
print(df)
```
输出:
```
A B
0 1 3
2 5 6
```
在使用`drop`方法时,需要指定`axis`参数的值。如果要删除一行数据,`axis`的值应该为`0`,如果要删除一列数据,`axis`的值应该为`1`。