pandas设置索引

Python种数据怎么添加“月份”、“合计”列索引,以便后续可视化

运行结果及详细
df2 = pd.read_excel(r.'cwal2.xlsx', sheet_name='2019')
df2 = df2.iloc[:, 2:].sum(axis=0)
print(df2)
1166848788
2169167214
3162948175
4171300090
5157206659
6157319074
7167763545
8163102634
9169177852
10164158305
11163826074
12165772766
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()