我有一個 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
提交
取消