熊猫行列转换

时间:2020-08-11 15:02:31

标签: python pandas

我有一个datframe,当前是:

df = pd.DataFrame(data=[[1,2,3],[4,5,6],[7,8,9]], columns=['name_one','name_two','name_three'], index=["2020-01-01", "2020-02-01", "2020-03-01"])
df

          name_one  name_two name_three
2020-01-01    1           2      3
2020-02-01    4           5      6
2020-03-01    7           8      9

有什么方法可以将其修改为:

df

          date  name      val
0   2020-01-01  name_one    1
1   2020-02-01  name_one    4
2   2020-03-01  name_one    7
3   2020-01-01  name_two    2
4   2020-02-01  name_two    5
5   2020-03-01  name_two    8
6   2020-01-01  name_three  3
7   2020-02-01  name_three  6
8   2020-03-01  name_three  9

3 个答案:

答案 0 :(得分:1)

使用pandas.melt

import pandas as pd

df = pd.DataFrame(data=[[1,2,3],[4,5,6],[7,8,9]], columns=['name_one','name_two','name_three'], index=["2020-01-01", "2020-02-01", "2020-03-01"])

df = df.reset_index().melt(id_vars='index', value_name="val")
df.columns = ['date', 'name', 'val']
print(df)

输出:

      date        name     val
0  2020-01-01    name_one    1
1  2020-02-01    name_one    4
2  2020-03-01    name_one    7
3  2020-01-01    name_two    2
4  2020-02-01    name_two    5
5  2020-03-01    name_two    8
6  2020-01-01  name_three    3
7  2020-02-01  name_three    6
8  2020-03-01  name_three    9

答案 1 :(得分:0)

尝试做:

(df.unstack().reset_index()
   .rename({'level_0': 'name', 0: 'val', 'level_1': 'date'}, axis=1))

答案 2 :(得分:0)

daphne ... project.asgi:application