亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Pandas groupby 并在列表中獲取字典

Pandas groupby 并在列表中獲取字典

LEATH 2021-09-25 10:19:27
我正在嘗試提取分組的行數據以使用值將其與另一個文件的標簽顏色一起繪制。我的數據框如下所示。df = pd.DataFrame({'x': [1, 4, 5], 'y': [3, 2, 5], 'label': [1.0, 1.0, 2.0]})    x   y   label0   1   3   1.01   4   2   1.02   5   5   2.0我想獲得一組標簽列表,例如{'1.0': [{'index': 0, 'x': 1, 'y': 3}, {'index': 1, 'x': 4, 'y': 2}], '2.0': [{'index': 2, 'x': 5, 'y': 5}]}這該怎么做?
查看完整描述

9 回答

?
楊__羊羊

TA貢獻1943條經驗 獲得超7個贊

您可以使用itertuples和defulatdict:


itertuples 返回命名元組以迭代數據幀:


for row in df.itertuples():

    print(row)

Pandas(Index=0, x=1, y=3, label=1.0)

Pandas(Index=1, x=4, y=2, label=1.0)

Pandas(Index=2, x=5, y=5, label=2.0)

所以利用這一點:


from collections import defaultdict

dictionary = defaultdict(list)

for row in df.itertuples():

    dummy['x'] = row.x

    dummy['y'] = row.y

    dummy['index'] = row.Index

    dictionary[row.label].append(dummy)


dict(dictionary)

> {1.0: [{'x': 1, 'y': 3, 'index': 0}, {'x': 4, 'y': 2, 'index': 1}],

 2.0: [{'x': 5, 'y': 5, 'index': 2}]}


查看完整回答
反對 回復 2021-09-25
  • 9 回答
  • 0 關注
  • 455 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號