我有一个两级多级的数据。下面是它的一个例子。我有两个参与者报告了他们两天的水果消费量。
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
发布于 2020-09-25 08:25:42
如果你指的是Python的pandas
DataFrame
,那么我已经为它编写了下一个解决方案,有点通用,不仅针对需要重新排列的两列苹果/橙色,而且针对任意数量的列,通过在脚本开头指定范围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[:, icol, 1] = a[:, 1]
b[:, icol, 2] = df.columns[crng[0] + icol]
b[:, icol, 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)
https://stackoverflow.com/questions/64060104
复制