保留现有列并将行转换为列
Keep the existing columns and convert the row to column
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
使用pivot_table
:
df = df.pivot_table(index= 'Ticker', columns='Attribute', values = 'Value')
示例数据框:
df = pd.DataFrame({
'Ticker': list('AAAAABBBB'),
'Key': list('112341234'),
'Value':list('ZQWERQWER')
})
按您的索引和键处理重复组,并以您喜欢的任何方式聚合您的组。这里我先用,你也可以用list
累加整组,例如:
df = df.groupby(['Ticker', 'Key'])['Value'].first().reset_index()
然后,最后,旋转 table:
df = df.pivot(index='Ticker', columns='Key', values='Value').reset_index()
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
使用pivot_table
:
df = df.pivot_table(index= 'Ticker', columns='Attribute', values = 'Value')
示例数据框:
df = pd.DataFrame({
'Ticker': list('AAAAABBBB'),
'Key': list('112341234'),
'Value':list('ZQWERQWER')
})
按您的索引和键处理重复组,并以您喜欢的任何方式聚合您的组。这里我先用,你也可以用list
累加整组,例如:
df = df.groupby(['Ticker', 'Key'])['Value'].first().reset_index()
然后,最后,旋转 table:
df = df.pivot(index='Ticker', columns='Key', values='Value').reset_index()