【问题标题】:Python hierarchy - multiple levelPython 层次结构 - 多层次
【发布时间】:2021-06-23 16:16:51
【问题描述】:

我有这个数据框,

ID Attachment
800 700
700 330
330 220
220 110
110 NULL

我想要这个结果

ID Level1 Level2 Level3 Level4
800 700 330 220 110

有人可以帮助我,非常感谢。

【问题讨论】:

  • 你试过什么?你试过自己解决一次吗?你之前也没问过same question吗?
  • 是的,我试过了,但我是 python 新手
  • 将其包含在您的问题中。

标签: python hierarchy


【解决方案1】:

假设 df 是您的数据框变量,这样的事情应该可以工作。

ids = set(df[df["Attachment"].isna()]["ID"])
levels = {0: ids} # Gets the last level
df = df[~df["Attachment"].isna()]
i=0
while len(df)>0: # Gets the previous levels
    i -= 1
    mask = df["Attachment"].isin(levels[i+1])
    ids = set(df[mask]["ID"])
    levels[i] = ids 
    df = df[~mask]

levels_df = pd.DataFrame({f"Level{-i-j}": list(levels[-j]) for j in range(1-i)})
levels_df.rename(columns={"Level0": "ID"}, inplace=True)

【讨论】:

    猜你喜欢
    • 2014-07-23
    • 1970-01-01
    • 1970-01-01
    • 2011-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-19
    相关资源
    最近更新 更多