3、用pandas自行构造数据DataFrame,在该数据上分别完成增删改查四个操作,分别对每一个操作加上注释。
时间: 2024-03-21 08:41:54 浏览: 51
好的,以下是对应的代码及注释:
```python
import pandas as pd
# 构造数据
data = {'name': ['Alice', 'Bob', 'Charlie', 'David'],
'age': [25, 30, 35, 40],
'gender': ['F', 'M', 'M', 'M']}
df = pd.DataFrame(data)
# 输出原始数据
print('Original DataFrame:\n', df)
# 增加数据
new_data = {'name': 'Emma', 'age': 27, 'gender': 'F'}
df = df.append(new_data, ignore_index=True)
print('After adding data:\n', df)
# 删除数据
df = df.drop(index=1)
print('After deleting data:\n', df)
# 修改数据
df.at[2, 'name'] = 'Charlie Brown'
df.loc[df['age'] == 40, 'gender'] = 'F'
print('After modifying data:\n', df)
# 查询数据
result = df.loc[df['age'] > 30]
print('Query results:\n', result)
```
输出结果如下:
```
Original DataFrame:
name age gender
0 Alice 25 F
1 Bob 30 M
2 Charlie 35 M
3 David 40 M
After adding data:
name age gender
0 Alice 25 F
1 Bob 30 M
2 Charlie 35 M
3 David 40 M
4 Emma 27 F
After deleting data:
name age gender
0 Alice 25 F
2 Charlie 35 M
3 David 40 M
4 Emma 27 F
After modifying data:
name age gender
0 Alice 25 F
2 Charlie Brown 35 M
3 David 40 F
4 Emma 27 F
Query results:
name age gender
2 Charlie Brown 35 M
3 David 40 F
```
阅读全文