【问题标题】:Reverse of melt and drop duplicates dataframe融化和丢弃重复数据帧的反转
【发布时间】:2022-01-08 17:31:55
【问题描述】:

我有一个类似的 DataFrame

event   entity  type
1       T1      Table
1       C1      Cell
1       C2      Cell
2       T2      Table
2       C3      Cell

我想把它转换成这样的东西

event   Table   Cell
1       T1      C1
1       T1      C2
2       T2      C3

这是 pd.melt 和 drop_duplicates() 的输出,我读到 Melt 的对立面是枢轴,因此尝试以这种方式处理单个事件。

df.pivot_table(values='entity', index='event', columns='type')

但这会引发DataError: No numeric types to aggregate 的错误,这很明显,因为 pivot 会按聚合进行分组,并且不会复制每个组合。知道这种操作到底可以做什么吗?请注意我为了简化而丢弃的 groupby 东西。

【问题讨论】:

    标签: python python-3.x pandas pivot melt


    【解决方案1】:

    使用Series.where 将非Table 行替换为NaNs 并转发填充缺失值,然后在boolean indexing、rename 列中通过~ 过滤掉这些带有倒置掩码的行并更改顺序列:

    m = df['type'].eq('Table')
    df['Table'] = df['entity'].where(m).ffill()
    df = df[~m].rename(columns={'entity':'Cell'})[['event','Table','Cell']]
    print (df)
       event Table Cell
    1      1    T1   C1
    2      1    T1   C2
    4      2    T2   C3
    

    【讨论】:

      猜你喜欢
      • 2021-11-21
      • 2021-10-06
      • 1970-01-01
      • 2017-05-19
      • 2021-12-12
      • 2018-01-06
      • 1970-01-01
      • 1970-01-01
      • 2018-09-02
      相关资源
      最近更新 更多