我有一个具有以下结构的 csv 文件:
我写了这段代码:
import pandas as pd
import plotly.express as px
input_file = "inf.csv"
df = pd.read_csv(input_file)
fig = px.bar(df,
x='Date',
y='User',
title='Test',
color='Items',
barmode='stack')
fig.show()
我想在 Y 轴上放置的不是用户数,而是一个计算同一天存在多少用户的数字。 我怎样才能做到这一点?
最佳答案
您可以使用df.groupby('Date').count().reset_index()
获取所需的数据结构。
plotly :
代码:
import pandas as pd
from plotly.subplots import make_subplots
import plotly.express as px
import plotly.graph_objs as go
import plotly.io as pio
#pio.renderers.default = 'jupyterlab'
# Sample data
d={'Date': ['01/08/2019', '01/08/2019', '07/08/2019', '12/08/2019',
'26/08/2019', '29/08/2019', '29/08/2019'],
'User':['U1', 'U2', 'U3', 'U4', 'U5', 'U6', 'U7'],
'Items': ['Pen', 'Ruler', 'Rubber', 'Rubber', 'Ruler', 'Ruler', 'Pen']
}
# data strucutre
df=pd.DataFrame(d)
dfg=df.groupby('Date').count().reset_index()
dfg=dfg.rename(columns={"User": "Users"})
# plot structure
fig = px.bar(dfg,
x='Date',
y='Users',
title='Test',
#color='Items',
barmode='stack')
# plot
fig.show()
关于Python Plotly 条形图对 csv 中的项目进行计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57954510/