我有一个 11 行 x 17604 列的数据框。随着我更改聚类,行数可能会有所不同。 B42D2033/26 G02B27/2214 G02F1/133753 G02F1/133707 G02F1/1341 G02F1/1339 G02F1/133371 G02B6/005 C08G73/12 G02F1/1303 ... G06F17/30035 G06F21/629 B65B3/26 E04D13/00 G06F17/30952 G07C9/00912 F02C9/28 G06F17/28 G06F17/30964 G06F21/82Cluster C1 0.000000 1.000000 0.000000 0.000000 0.000000 1.000000 0.000000 0.000000 0.000000 0.000000 ... 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000C10 0.000000 3.250000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 ... 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000C11 0.020619 1.149485 0.262887 0.829897 0.551546 1.030928 0.082474 1.175258 0.005155 0.216495 ... 0.005155 0.010309 0.005155 0.005155 0.005155 0.005155 0.005155 0.005155 0.005155 0.005155我想根据列中的值为每个集群生成一个字典或系列。例如,值!=0可能看起来的所有列,以字典形式显示,例如:{'C1', ['G02B27/2214', 'G02F1/1339']}如何为值等于“某个值”或值范围的每个集群行生成一个系列?我确实查看了根据 pandas 中列中的值从 DataFrame中选择行,但该解决方案不适用于一行中的所有列。编辑:我意识到我可以转置df并执行以下操作:df_clusters.T[df_clusters.T['C1']>0]它返回df'C1' 大于 0 的每一行。我想我可以删除其他簇列,但我认为这不是最好的解决方案。
2 回答

繁华开满天机
TA贡献1816条经验 获得超4个赞
想法是为每个条件创建值的索引,然后创建新的 DataFrame 并indices在列表中获取每个列表,然后转换为dict:
i, c = np.where(df > 0)
d = pd.DataFrame({'a':df.index[i], 'b':df.columns[i]}).groupby('a')['b'].apply(list).to_dict()
print (d)
另一种解决方案是使用DataFrame.stackorDataFrame.melt重塑,通过boolean indexingor过滤DataFrame.query,最后使用以下方法创建 l ists dict:
s = df.stack()
d = s[s > 0].reset_index().groupby('Cluster')['level_1'].apply(list).to_dict()
d = (df.reset_index()
.melt('Cluster', value_name='v1', var_name='v2')
.query('v1 > 0')
.groupby('Cluster')['v2']
.apply(list)
.to_dict())
添加回答
举报
0/150
提交
取消