Python种数据怎么添加“月份”、“合计”列索引,以便后续可视化
df2 = pd.read_excel(r.'cwal2.xlsx', sheet_name='2019')
df2 = df2.iloc[:, 2:].sum(axis=0)
print(df2)
1月 166848788
2月 169167214
3月 162948175
4月 171300090
5月 157206659
6月 157319074
7月 167763545
8月 163102634
9月 169177852
10月 164158305
11月 163826074
12月 165772766
dtype: int64
```报错内容
尝试用df2 = df2.reset_index()重新设置了索引,但是在作图时索引依旧是无效的
求解!!
望采纳
可以使用 Pandas 的 DataFrame 函数来将数据转换为 DataFrame,然后使用 reset_index 函数重新设置索引。例如:
import pandas as pd
# 读取 Excel 文件中的数据
df2 = pd.read_excel(r.'cwal2.xlsx', sheet_name='2019')
# 计算每一列的合计值
df2 = df2.iloc[:, 2:].sum(axis=0)
# 将结果转换为 DataFrame
df2 = pd.DataFrame(df2)
# 重新设置索引,并添加 "月份" 列和 "合计" 列
df2 = df2.reset_index(name="合计")
df2.rename(columns={"index": "月份"}, inplace=True)
print(df2)
如果想要在可视化时使用这些索引,可以在调用可视化函数时将这些索引作为参数传递。例如,在使用 Matplotlib 绘制柱状图时,可以将“月份”列作为 x 轴,“合计”列作为 y 轴:
import matplotlib.pyplot as plt
# 绘制柱状图
plt.bar(df2["月份"], df2["合计"])
# 显示图像
plt.show()