问题描述
我有两级多级数据。下面是一个示例。我有两个参与者报告了他们两天的水果消费量。
id day apple orange
1 1 34 12
1 2 54 43
2 1 65 56
2 2 87 81
我想将数据帧从2级数据重组为3级数据。我想a)为水果类型做一个变量; b)将一天中的嵌套水果消耗量在一列中显示。因此,数据框如下所示:
id day fruit_type fruit_consumption
1 1 apple 34
1 1 orange 12
1 2 apple 54
1 2 orange 43
2 1 apple 65
2 1 orange 56
2 2 apple 87
2 2 orange 81
解决方法
如果您是指Python的pandas
DataFrame
,那么我已经为它编写了下一个解决方案,有点通用,不仅适用于需要重新排列的Apple / Orange两列,而且适用于任意数量的列,通过在脚本开头指定范围crng
来控制。应该可以快速运行,因为它使用了普通的numpy
并进行了少量的python循环迭代。
您也可以try next code online here!。
import pandas as pd,numpy as np
crng = (2,4) # Range of columns for rearranging
df = pd.DataFrame([map(int,line.split()) for line in """
1 1 34 12
1 2 54 43
2 1 65 56
2 2 87 81
""".splitlines() if line.strip()],columns = ['id','day','apple','orange'])
print('input:\n',df)
a = df.values
b = np.zeros((a.shape[0],crng[1] - crng[0],crng[0] + 2),dtype = np.object_)
for icol,col in enumerate(df.columns[crng[0] : crng[1]]):
b[:,icol,0] = a[:,0]
b[:,1] = a[:,1]
b[:,2] = df.columns[crng[0] + icol]
b[:,3] = a[:,crng[0] + icol]
b = b.reshape((b.shape[0] * b.shape[1],b.shape[2]))
df = pd.DataFrame(data = b,columns = df.columns[:crng[0]].values.tolist() + ['fruit_type','fruit_consumption'],)
print('output:\n',df)