gpt4 book ai didi

python - 使用 pandas 或 numpy 将数据拆分为 'classes'

转载 作者:行者123 更新时间:2023-11-28 17:23:18 25 4
gpt4 key购买 nike

我有大约 1000 列的大型 csv 数据文件,我希望将所有行拆分为所谓的类。 “类”包含在相同位置具有零和非零的行。

例如:文件:

0  ,0,0.1,0.2,0
0.9,0,0.3,0.2,0
0 ,0,0.8,0.2,0
0 ,0,0.2,0 ,0
0 ,0,0.1,0.2,0

将被分成三类:第 1、3、5 行;第 2 行;第 4 行。

如何使用 pandas 或 numpy 高效地完成这项工作?

最佳答案

你可以这样做:

In [38]: dfs = []
...: for _, g in df.groupby(((df == 0)*1).astype(str).sum(axis=1)):
...: print(g)
...: dfs.append(g)
...:
0 1 2 3 4
1 0.9 0 0.3 0.2 0
0 1 2 3 4
0 0.0 0 0.1 0.2 0
2 0.0 0 0.8 0.2 0
4 0.0 0 0.1 0.2 0
0 1 2 3 4
3 0.0 0 0.2 0.0 0

In [39]: dfs
Out[39]:
[ 0 1 2 3 4
1 0.9 0 0.3 0.2 0, 0 1 2 3 4
0 0.0 0 0.1 0.2 0
2 0.0 0 0.8 0.2 0
4 0.0 0 0.1 0.2 0, 0 1 2 3 4
3 0.0 0 0.2 0.0 0]

检查:

In [44]: [x.index.tolist() for x in dfs]
Out[44]: [[1], [0, 2, 4], [3]]

解释:

In [40]: df == 0
Out[40]:
0 1 2 3 4
0 True True False False True
1 False True False False True
2 True True False False True
3 True True False True True
4 True True False False True

In [41]: ((df == 0)*1)
Out[41]:
0 1 2 3 4
0 1 1 0 0 1
1 0 1 0 0 1
2 1 1 0 0 1
3 1 1 0 1 1
4 1 1 0 0 1

In [42]: ((df == 0)*1).astype(str).sum(axis=1)
Out[42]:
0 11001.0
1 1001.0
2 11001.0
3 11011.0
4 11001.0
dtype: float64

关于python - 使用 pandas 或 numpy 将数据拆分为 'classes',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40481311/

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