【问题标题】:Dataframe to Sankey Diagram数据框到桑基图
【发布时间】:2020-11-27 18:36:46
【问题描述】:

我想根据如下所示的产品数据生成桑基图。

   id  begin_date   status  
   1   01.02.2020   a       
   1   10.02.2020   b       
   1   17.02.2020   c       
   2   02.02.2020   d       
   2   06.03.2020   b       
   2   17.04.2020   c    

为了您的实验:

pd.DataFrame([[1, '2020-02-01', 'a'], [1, '2020-02-10', 'b'], [1, '2020-02-17', 'c'], [2, '2020-02-02', 'd'], [2, '2020-03-06', 'b'],[2, '2020-04-17', 'c']], columns=['id', 'begin_date', 'status'])

看了这个解释后: Draw Sankey Diagram from dataframe 我想构建看起来像这样的“源-目标-值”-Dataframe。为了加深理解,我没有将 Source 和 Target 转换为整数。

# with Source = previous status
# with Target = next status
# with Value = count of IDs that transition from Source to Target
Source  Target      Value      Link Color
     a       b          1      rgba(127, 194, 65, 0.2)
     b       c          2      rgba(127, 194, 65, 0.2)
     d       b          1      rgba(211, 211, 211, 0.5)

问题在于生成源、目标和值。 SourceTarget 应该是从ab 的状态转换。 Value 是进行该转换的 ids 的计数。

最好的方法是什么?

编辑:使用在线生成器,结果将如下所示:

【问题讨论】:

    标签: python pandas sankey-diagram


    【解决方案1】:

    找到答案了!

    # assuming df is sorted by begin_date
    import pandas as pd
    df = pd.read_csv(r"path")
    dfs = []
    unique_ids = df["id"].unique()
    for uid in unique_ids:
        df_t = df[df["id"] == uid].copy()
        df_t["status_next"] = df_t["status"].shift(-1)
        df_t["status_append"] = df_t["status"] +  df_t["status_next"]
        df_t = df_t.groupby("status_append").agg(Value=("status_append","count")).reset_index()
        dfs.append(df_t)
    
    df = pd.concat(dfs, ignore_index=True)
    df = df.groupby("status_append").agg(Value=("Value","sum")).reset_index()
    
    df["Source"] = df['status_append'].astype(str).str[0]
    df["Target"] = df['status_append'].astype(str).str[1]
    df = df.drop("status_append", axis=1)
    df = df[["Source", "Target", "Value"]]
    

    产量

    Source  Target  Value
    a            b      1
    b            c      2
    d            b      1
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-02
      • 2019-10-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-06
      相关资源
      最近更新 更多