使用列数可视化线图

2024-04-18

我有个问题。我有两列toDate and fromDate。我想直观地看到它们之间的差异linechart。 x 轴应该是月份,例如(1、2、3、4 等),y 轴应该是月份的计数。最后这应该是由what。不幸的是我没有得到想要的输出。

数据框

    id  toDate  fromDate
0   1   2021-03-22T18:59:59Z    2021-02-22
1   2   None    2021-03-18
2   3   2021-04-22T18:59:59Z    2021-03-22
3   4   2021-02-15T18:59:59Z    2021-02-10
4   5   2021-09-15T18:59:59Z    2021-09-07
5   6   2020-01-12T18:59:59Z    None
6   7   2022-02-22T18:59:59Z    2022-01-18

Code

import pandas as pd
import seaborn as sns
d = {'id': [1, 2, 3, 4, 5, 6, 7],
     'toDate': ['2021-03-22T18:59:59Z', None, '2021-04-22T18:59:59Z', 
'2021-02-15T18:59:59Z', '2021-09-15T18:59:59Z', '2020-01-12T18:59:59Z', '2022-02-22T18:59:59Z'],
     'fromDate': ['2021-02-22', '2021-03-18', '2021-03-22', 
'2021-02-10', '2021-09-07', None, '2022-01-18']
    }
df = pd.DataFrame(data=d)
display(df)
df_new = pd.DataFrame()
df_new['toDate_month']  = pd.to_datetime(df['toDate'], errors='coerce').dt.month
df_new['fromDate_month']  = pd.to_datetime(df['fromDate'], errors='coerce').dt.month

df_new.melt(var_name='what', value_name='month')

我想要的是

sns.lineplot(data=df_new, x="month", y="month".value_counts(), hue="what")

IIUC,你可以通过pandas.crosstab https://pandas.pydata.org/docs/reference/api/pandas.crosstab.html数据帧到sns.lineplot https://seaborn.pydata.org/generated/seaborn.lineplot.html它将处理宽格式,作为索引的“x”和列的“hue”:

sns.lineplot(data=pd.crosstab(df_new['month'], df_new['what']))

output:

交叉表:

what   fromDate_month  toDate_month
month                              
1.0                 1             1
2.0                 2             2
3.0                 2             1
4.0                 0             1
9.0                 1             1
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用列数可视化线图 的相关文章

随机推荐