【问题标题】:Keep the existing columns and convert the row to column [duplicate]保留现有列并将行转换为列[重复]
【发布时间】:2021-08-10 17:14:59
【问题描述】:

dataFrame Ticker、Attribute 和 Value 一共有三列。

The original dataFrame can be seen here

我想将属性值设置为一列,这可以通过将其设置为索引然后进行转置来轻松完成,但问题是我想在进行转置时将 Ticker 保留为列行。 When I take Attribute as an index and take its transpose

当我将两者都设置为索引然后进行转置时,它看起来像这样,我不想要 When both the Attribute and Ticker taken as index and transposed

我想要的是这个 The required output

【问题讨论】:

    标签: python pandas dataframe dataset data-science


    【解决方案1】:

    使用pivot_table:

    df = df.pivot_table(index= 'Ticker', columns='Attribute', values = 'Value')
    

    【讨论】:

    • 我尝试时值列不是数字,它会抛出错误 DataError: No numeric types to aggregate
    • 对我也不起作用,不知道为什么这是公认的答案。
    【解决方案2】:

    示例数据框:

    df = pd.DataFrame({
        'Ticker': list('AAAAABBBB'),
        'Key': list('112341234'),
        'Value':list('ZQWERQWER')
    })
    

    通过您的索引和键处理重复组,并以您喜欢的任何方式聚合您的组。这里我先用,你也可以用list累加整个组,例如:

    df = df.groupby(['Ticker', 'Key'])['Value'].first().reset_index()
    

    然后,最后,旋转表格:

    df = df.pivot(index='Ticker', columns='Key', values='Value').reset_index()
    

    【讨论】:

    • Ticker contains duplicates pivot 不允许重复,所以当我尝试删除重复项时,我只留下了单列市值
    • 虽然此代码可能会回答问题,但提供有关它如何和/或为什么解决问题的额外上下文将提高​​答案的长期价值。
    • @AdnanKhan - 编辑了答案并添加了一些处理重复项的代码。如果还有什么需要澄清的,请告诉我。
    • @rudolfovic 谢谢我试图连接两个数据帧,所以我在两个数据帧上分别应用了枢轴,并在旋转后加入对我有用
    猜你喜欢
    • 1970-01-01
    • 2021-12-23
    • 2013-10-01
    • 1970-01-01
    • 2023-03-14
    • 2015-08-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多