【问题标题】:Create df that holds column name and corresponding value of another dataframe创建包含另一个数据框的列名和相应值的 df
【发布时间】:2019-03-07 16:03:53
【问题描述】:

我创建了以下名为df的数据框

       col1  col2  col3
    0     4     5     2
    1     5     2     4
    2     3    10     3
    3     6     2     2
    4     3     2     4 

我现在想要的是翻转行,使 df 看起来像这样:

         column_name  value
    0        col1      4
    1        col2      5
    2        col3      2
    3        col1      5
    4        col2      2
    5        col3      4
   ...       ...      ...

我想我需要使用stack(),但我不确定如何使用。我已经尝试了以下

df = df.stack().rename_axis(['column_name']).reset_index(name = 'value')

但返回以下错误

raise ValueError('Length of names must match number of levels in '
ValueError: Length of names must match number of levels in MultiIndex.

问题:如何堆叠这些值以获得所需的数据帧?

【问题讨论】:

标签: python python-3.x pandas dataframe


【解决方案1】:

这里需要用reset_indexdrop=True去掉MultiIndex的第一层:

df = (df.stack()
        .reset_index(level=0, drop=True)
        .rename_axis(['column_name'])
        .reset_index(name = 'value'))
print (df)
   column_name  value
0         col1      4
1         col2      5
2         col3      2
3         col1      5
4         col2      2
5         col3      4
6         col1      3
7         col2     10
8         col3      3
9         col1      6
10        col2      2
11        col3      2
12        col1      3
13        col2      2
14        col3      4

另一个解决方案是melt,值的顺序发生了变化:

df = df.melt(var_name='column_name')
print (df)
   column_name  value
0         col1      4
1         col1      5
2         col1      3
3         col1      6
4         col1      3
5         col2      5
6         col2      2
7         col2     10
8         col2      2
9         col2      2
10        col3      2
11        col3      4
12        col3      3
13        col3      2
14        col3      4

【讨论】:

  • 感谢您的回复,但我的意思不是有两个名为“列”和“名称”的列。我只想要一个名为“column_name”的列
【解决方案2】:

如果行的顺序不重要,您可以直接使用pd.melt

res = pd.melt(df, var_name='column_name')

如果您希望按输入行排序,可以使用pd.meltreset_index 将索引提升到一个系列,然后使用sort_values

res = pd.melt(df.reset_index(), id_vars='index', var_name='column_name')\
        .sort_values('index').drop('index', 1).reset_index(drop=True)

print(res)

   column_name  value
0         col1      4
1         col2      5
2         col3      2
3         col1      5
4         col2      2
5         col3      4
6         col1      3
7         col2     10
8         col3      3
9         col1      6
10        col2      2
11        col3      2
12        col1      3
13        col2      2
14        col3      4

【讨论】:

    猜你喜欢
    • 2019-11-20
    • 2020-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-13
    • 1970-01-01
    • 2019-01-20
    • 1970-01-01
    相关资源
    最近更新 更多