pandas 添加行 汇总
时间: 2023-11-09 15:00:36 浏览: 38
可以使用 `append()` 方法向 Pandas DataFrame 中添加行,可以先定义一个字典,然后使用 `append()` 方法添加到 DataFrame 中。例如:
```
import pandas as pd
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})
new_row = {'A': 4, 'B': 7}
df = df.append(new_row, ignore_index=True)
print(df)
```
输出:
```
A B
0 1 4
1 2 5
2 3 6
3 4 7
```
使用 `ignore_index=True` 可以让索引自动递增。
汇总可以使用 `groupby()` 方法,根据需要对特定列进行汇总统计。例如:
```
import pandas as pd
df = pd.DataFrame({'name': ['Alice', 'Bob', 'Charlie', 'Alice'],
'age': [25, 30, 35, 40],
'salary': [5000, 6000, 7000, 8000]})
grouped = df.groupby('name').agg({'age': 'mean', 'salary': 'sum'})
print(grouped)
```
输出:
```
age salary
name
Alice 32.5 13000
Bob 30.0 6000
Charlie 35.0 7000
```
这里使用了 `agg()` 方法对每个分组进行聚合统计,例如对年龄列使用 `mean` 函数求平均值,对薪资列使用 `sum` 函数求和。