python - 恢复频率表

标签 python pandas pivot-table

假设您有一个包含如下频率信息的 pandas DataFrame:

data = [[1,1,2,3],
        [1,2,3,5],
        [2,1,6,1],
        [2,2,2,4]]
df = pd.DataFrame(data, columns=['id', 'time', 'CountX1', 'CountX2'])

# id    time    CountX1     CountX2
# 0     1   1   2   3
# 1     1   2   3   5
# 2     2   1   6   1
# 3     2   2   2   4

我正在寻找一个简单命令(例如使用pd.pivotpd.melt())将这些频率恢复为tidy data应该是这样的:

id time variable
0   1   X1
0   1   X1
0   1   X2
0   1   X2
0   1   X2
1   1   X1
1   1   X1
1   1   X1
1   1   X2 ...  # 5x repeated
2   1   X1 ...  # 6x repeated
2   1   X2 ...  # 1x repeated
2   2   X1 ...  # 2x repeated
2   2   X2 ...  # 4x repeated

最佳答案

你需要:

a = df.set_index(['id','time']).stack()
df = a.loc[a.index.repeat(a)].reset_index().rename(columns={'level_2':'a'}).drop(0, axis=1)
print(df)
    id  time        a
0    1     1  CountX1
1    1     1  CountX1
2    1     1  CountX2
3    1     1  CountX2
4    1     1  CountX2
5    1     2  CountX1
6    1     2  CountX1
7    1     2  CountX1
8    1     2  CountX2
9    1     2  CountX2
10   1     2  CountX2
11   1     2  CountX2
12   1     2  CountX2
13   2     1  CountX1
14   2     1  CountX1
15   2     1  CountX1
16   2     1  CountX1
17   2     1  CountX1
18   2     1  CountX1
19   2     1  CountX2
20   2     2  CountX1
21   2     2  CountX1
22   2     2  CountX2
23   2     2  CountX2
24   2     2  CountX2
25   2     2  CountX2

第一个解决方案首先被删除,因为顺序不同:

a = df.melt(['id','time'])
df = (a.loc[a.index.repeat(a['value'])]
       .drop('value', 1)
       .sort_values(['id', 'time'])
       .reset_index(drop=True))

关于python - 恢复频率表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48459465/

相关文章:

Python 比较两个十六进制值

python - Flask with Gunicorn on nginx 502 bad gateway 错误

来自多列的 python 日期和日期时间

python - groupby 并根据另一列的值保留一列的信息

python - reshape 数据框并对每行应用计算

mysql - 试图用它们之间的枢轴填充两个表

Excel VBA - 一次选择多个切片器项目而无需刷新

python - 如何在Windows中使用python以用户身份创建进程?

Python 2.7 Unicode/IDLE 混淆

python - 从 pandas DataFrame 中高效扩展行