熊猫:如何将这种宽格式数据转换为长格式

时间:2020-07-09 13:20:54

标签: python pandas

我正在寻找一种将数据从“宽”结构转换为数据框的有效方法。

数据: 我们有不同的观测值,每个观测值都有不同日期的特征数据。 理想的数据帧将包含以下列:observation_id,day,feature_1,feature_2,...。

当前数据结构: 词典列表。每个字典代表一个观察。 在每本词典中,我们都有键“ observation_id”,以及所有天和所有功能的天+要素ID的粘贴键。

例如:

# Input:
x = [{'observation_id': '1', '0.feature_1': 2, '0.feature_2': 2, '1.feature_1': 3, '1.feature_2': 1},
     {'observation_id': '2', '0.feature_1': 7, '0.feature_2': 3, '1.feature_1': 4, '1.feature_2': 2},
     {'observation_id': '3', '0.feature_1': 5, '0.feature_2': 2, '1.feature_1': 5, '1.feature_2': 3}]

# Desired output:
  observation_id  day  feature_1  feature_2
0              1    0          2          2
1              1    1          3          1
2              2    0          7          3
3              2    1          4          2
4              3    0          5          2
5              3    1          5          3
                                                        

我尝试了以下操作,但没有得到期望的结果

df = pd.DataFrame(x)    
pd.wide_to_long(df, stubnames=["0", "1"], i="observation_id", j="feature", sep=".", suffix='\w+').reset_index()

# output:
  observation_id    feature  0  1
0              1  feature_1  2  3
1              2  feature_1  7  4
2              3  feature_1  5  5
3              1  feature_2  2  1
4              2  feature_2  3  2
5              3  feature_2  2  3

有什么想法吗?

谢谢!

1 个答案:

答案 0 :(得分:1)

尝试添加stackunstack

df = pd.DataFrame(x)    
yourdf = pd.wide_to_long(df, stubnames=["0", "1"], i="observation_id", j="feature", sep=".", suffix='\w+').\
              stack().unstack(1).reset_index()