gpt4 book ai didi

python - 在 Python 中生成数据透视表

转载 作者:太空宇宙 更新时间:2023-11-04 10:11:23 25 4
gpt4 key购买 nike

假设我有 100 个文件,并循环遍历所有文件。在每个文件中,记录了几个属性:(读取所有文件之前不知道属性总数)

假设一个简单的情况,在读取所有文件后,我们获得了20个不同的属性和以下信息:

File_001: a1, a3, a5, a2
File_002: a1, a3
File_003: a4
File_004: a4, a2, a6
File_005: a7, a8, a9
...
File_100: a19, a20

[更新] 或者以另一种表示形式,其中每一行是一个文件和一个属性之间的单个匹配:

File_001: a1
File_001: a3
File_001: a5
File_001: a2
File_002: a1
File_002: a3
File_003: a4
File_004: a4
File_004: a2
File_004: a6
...
File_100: a19
File_100: a20

如何生成“反向”统计表,即:

a1: File_001, File_002, File_006, File_083
a2: File_001, File_004
...
a20: File_099, File_100

如何在 Python (2.7.x) 中执行此操作? (有或没有 Pandas。我认为 Pandas 可能会有所帮助)

最佳答案

UPDATE2:如何生成“反向”统计表

In [9]: df
Out[9]:
file attr
0 File_001 a1
1 File_001 a3
2 File_001 a5
3 File_001 a2
4 File_002 a1
5 File_002 a3
6 File_003 a4
7 File_004 a4
8 File_004 a2
9 File_004 a6
10 File_100 a19
11 File_100 a20

In [10]: df.groupby('attr')['file'].apply(list)
Out[10]:
attr
a1 [File_001, File_002]
a19 [File_100]
a2 [File_001, File_004]
a20 [File_100]
a3 [File_001, File_002]
a4 [File_003, File_004]
a5 [File_001]
a6 [File_004]
Name: file, dtype: object

更新:

How can I set output[202] as DataFrame?

new = (df.set_index('file')
.apply(lambda x: pd.Series(x['attr']), axis=1)
.stack()
.reset_index(level=1, drop=True)
.reset_index(name='attr')
.groupby('attr')['file']
.apply(list)
)

so I can export it to html or csv?

new.to_csv('/path/to/file.csv', index=False)

html_text = new.to_html(index=False)

原答案:

这是一个 Pandas 解决方案:

原始DF:

In [201]: df
Out[201]:
file attr
0 File_001 [a1, a3, a5, a2]
1 File_002 [a1, a3]
2 File_003 [a4]
3 File_004 [a4, a2, a6]
4 File_005 [a7, a8, a9]
5 File_100 [a19, a20]

解决方法:

In [202]: %paste
(df.set_index('file')
.apply(lambda x: pd.Series(x['attr']), axis=1)
.stack()
.reset_index(level=1, drop=True)
.reset_index(name='attr')
.groupby('attr')['file']
.apply(list)
)
## -- End pasted text --

输出:

Out[202]:
attr
a1 [File_001, File_002]
a19 [File_100]
a2 [File_001, File_004]
a20 [File_100]
a3 [File_001, File_002]
a4 [File_003, File_004]
a5 [File_001]
a6 [File_004]
a7 [File_005]
a8 [File_005]
a9 [File_005]
Name: file, dtype: object

关于python - 在 Python 中生成数据透视表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38043535/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com