我有一个测试 excel 文件,如:
df = pd.DataFrame({'name':list('abcdefg'),
'age':[10,20,5,23,58,4,6]})
print (df)
name age
0 a 10
1 b 20
2 c 5
3 d 23
4 e 58
5 f 4
6 g 6
我使用 Pandas
和 matplotlib
来读取和绘制它:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import os
excel_file = 'test.xlsx'
df = pd.read_excel(excel_file, sheet_name=0)
df.plot(kind="bar")
plt.show()
它使用索引号作为项目名称,如何将其更改为存储在 name
列中的名称?
最佳答案
您可以在 plot.bar
中为 x
和 y
值指定列:
df.plot(x='name', y='age', kind="bar")
或者先通过DataFrame.set_index
创建Series
并选择 age
列:
df.set_index('name')['age'].plot(kind="bar")
#if multiple columns
#df.set_index('name').plot(kind="bar")
关于python-3.x - 更改 Pandas 中的栏项目名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55396062/