【发布时间】:2020-10-02 18:50:52
【问题描述】:
我的目标是从Pandas 数据框中的两个过滤列创建比率,然后使用Plotly Express 创建使用px.bar() 的条形图。我可以使用 Pandas 中的基本 plot() 函数,但不能使用 Plotly Express 中的 px.bar() 函数。
我遇到的一个问题是某些列包含重复值。这导致我不得不做一些 Pandas 体操。
这是我的数据:
test_df = pd.DataFrame({'Manufacturer':['Ford', 'Ford', 'Mercedes', 'BMW', 'Ford', 'Mercedes', 'BMW', 'Ford', 'Mercedes', 'BMW', 'Ford', 'Mercedes', 'BMW', 'Ford', 'Mercedes', 'BMW', 'Ford', 'Mercedes', 'BMW'],
'Metric':['Orders', 'Orders', 'Orders', 'Orders', 'Orders', 'Orders', 'Orders', 'Sales', 'Sales', 'Sales', 'Sales', 'Sales', 'Sales', 'Warranty', 'Warranty', 'Warranty', 'Warranty', 'Warranty', 'Warranty'],
'Sector':['Germany', 'Germany', 'Germany', 'Germany', 'USA', 'USA', 'USA', 'Germany', 'Germany', 'Germany', 'USA', 'USA', 'USA', 'Germany', 'Germany', 'Germany', 'USA', 'USA', 'USA'],
'Value':[45000, 70000, 90000, 65000, 40000, 65000, 63000, 2700, 4400, 3400, 3000, 4700, 5700, 1500, 2000, 2500, 1300, 2000, 2450],
'City': ['Frankfurt', 'Bremen', 'Berlin', 'Hamburg', 'New York', 'Chicago', 'Los Angeles', 'Dresden', 'Munich', 'Cologne', 'Miami', 'Atlanta', 'Phoenix', 'Nuremberg', 'Dusseldorf', 'Leipzig', 'Houston', 'San Diego', 'San Francisco']
})
由于一些重复值,我创建了一个临时表:
temp_table = test_df.reset_index().pivot_table(values = 'Value', index = ['Manufacturer', 'Metric', 'Sector'], aggfunc='sum')
然后,重置索引:
df_new = temp_table.reset_index()
那么,
s1 = df_new.set_index(['Manufacturer','Sector']).query("Metric=='Orders'").Value
s2 = df_new.set_index(['Manufacturer','Sector']).query("Metric=='Sales'").Value
然后,unstack 和 plot:
temp_frame = s1.div(s2).unstack()
temp_frame.plot(kind='bar')
这可以完美运行,并使用标准 Pandas plot() 函数生成以下条形图:
现在,我尝试使用 Plotly Express 中的 px.bar() 函数进行绘图:
px.bar(temp_frame, x='Sector', y='Value', color='Exchange',
barmode='group',
text='Value',
title='Order to Sales Ratio)
此代码导致以下错误消息:
ValueError: Value of 'x' is not the name of a column in 'data_frame'. Expected one of ['Germany', 'USA'] but received: Sector
此错误看起来与Use Pandas index in Plotly Express 中报告的问题有关。但是,我认为我的数据框的配置方式无法实现 @Laurens Koppenol 建议并由 @nicolaskruchten 验证的“丑陋修复”解决方案。
谁能帮我解决这个错误,以便我可以使用Plotly Express 创建上面的条形图?
提前致谢!
【问题讨论】:
-
您的数据框中似乎没有 Exchenge 列
-
应该是“制造商”列,而不是“交易所”。
-
替换
px.bar(temp_frame, x='Sector', y='Value', color='Manufacturer', barmode='group', text='Value', title='Order to Sales Ratio')时会得到同样的错误信息
标签: pandas plotly plotly-dash plotly-python