大家好,我有这个数据集:
import pandas as pd
# intialise data of lists.
data = {'Year':['2017', '2018', '2018', '2019'],'Month':['1', '1', '2', '3'],'Outcome':['dead', 'alive', 'alive', 'empty'], 'outcome_count':[20, 21, 19, 18]}
# Create DataFrame
dfy = pd.DataFrame(data)
# Print the output.
print(dfy)
我确实想根据期间(应该是月份和年份)绘制结果。现在,月份和年份位于不同的列上,我如何将它们组合起来,以便获得月份和年份的结果图表。传说应该有结果名称吗?
最佳答案
您可以通过 to_datetime
创建由日期时间填充的新列如果传递了 3 列 DataFrame,其中包含 Year
、Month
、Day
列,然后按 Series.dt.to_period
传递月份周期:
dfy['dates'] = pd.to_datetime(dfy[['Year','Month']].assign(Day=1))
dfy['per'] = dfy['dates'].dt.to_period('m')
print(dfy)
Year Month Outcome outcome_count dates per
0 2017 1 dead 20 2017-01-01 2017-01
1 2018 1 alive 21 2018-01-01 2018-01
2 2018 2 alive 19 2018-02-01 2018-02
3 2019 3 empty 18 2019-03-01 2019-03
然后可以用句点或日期时间绘制:
dfy.plot(x='per', y='outcome_count')
dfy.plot(x='dates', y='outcome_count')
关于python - Plotly:如何根据时间段绘制时间图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60070013/