【问题标题】:Manipulate a stacked dataframe in pandas在 pandas 中操作堆叠的数据框
【发布时间】:2021-06-16 07:51:50
【问题描述】:

我想将堆积的数据框转换为 Pandas 中的常规数据框。 原始df是:

Score Amy Brian Carl
test1 5 6 7
test2 3 2 4

堆叠后:

0
test1 Amy 5
Brian 6
Carl 7
test2 Amy 3
Brian 2
Carl 4

我想要的结果如下:

name score
test1 Amy 5
test1 Brian 6
test1 Carl 7
test2 Amy 3
test2 Brian 2
test2 Carl 4

任何建议将不胜感激!

【问题讨论】:

  • df.melt('Score', var_name='name', value_name='score')

标签: python pandas dataframe stack


【解决方案1】:

这比上面@Quang Hoang 的回答要长一点,但也应该如此。它在堆叠 DataFrame 后拾取

test1   Amy     5
test1   Brian   6
test1   Carl    7
test2   Amy     3
test2   Brian   2
test2   Carl    4

# Reset index to flatten DataFrame
result = df_stk.reset_index().copy()

    level_0 level_1 0
0   test1   Amy     5
1   test1   Brian   6
2   test1   Carl    7
3   test2   Amy     3
4   test2   Brian   2
5   test2   Carl    4

# Rename columns
result.rename(columns={'level_1':'name',
                       0: 'score'},inplace=True)

    level_0 name    score
0   test1   Amy     5
1   test1   Brian   6
2   test1   Carl    7
3   test2   Amy     3
4   test2   Brian   2
5   test2   Carl    4

# Set test values to index of DataFrame
result.index = result['level_0']

level_0 level_0 name    score
test1   test1   Amy     5
test1   test1   Brian   6
test1   test1   Carl    7
test2   test2   Amy     3
test2   test2   Brian   2
test2   test2   Carl    4

# Rename index to blank
result.index.name=''

       level_0  name    score
test1   test1   Amy     5
test1   test1   Brian   6
test1   test1   Carl    7
test2   test2   Amy     3
test2   test2   Brian   2
test2   test2   Carl    4

# Drop test column from DataFrame
result.drop(columns=['level_0'],inplace=True)

        name    score
test1   Amy     5
test1   Brian   6
test1   Carl    7
test2   Amy     3
test2   Brian   2
test2   Carl    4

【讨论】:

    猜你喜欢
    • 2023-01-11
    • 1970-01-01
    • 1970-01-01
    • 2021-04-10
    • 1970-01-01
    • 2022-08-23
    • 1970-01-01
    • 2020-08-04
    • 2019-10-18
    相关资源
    最近更新 更多