簡體   English   中英

從 pandas dataframe 創建字典,其值為元組

[英]Create dict from a pandas dataframe with values as tuple

我有一個像這樣的 dataframe:

>>> df = pd.DataFrame(np.array([[1, 2], ['a', 'b']]), columns=['col1', 'col2'])
>>> df
  col1 col2
0    1    2
1    a    b

我要做的是從這個 dataframe 創建一個字典,其中行索引是鍵,col1 和 col2 是我的字典的元組形式的值。 這是我正在做的,但這會返回一個列表:

>>> import numpy as np
>>> import pandas as pd
>>> df.T.to_dict('list')
{0: ['1', '2'], 1: ['a', 'b']}

這是我想要得到的:

{0: ('1', '2'), 1: ('a', 'b')}

我們試試看

df.agg(tuple,1).to_dict()

另一種方法是采用你有應用字典理解的字典:

>>> {k: tuple(v) for k, v in df.T.to_dict("list").items()}
{0: ('1', '2'), 1: ('a', 'b')}

不確定速度,但使用itertuples

dict(zip(df.index, df.itertuples(index=False, name=None)))
{0: ('1', '2'), 1: ('a', 'b')}

或者

dict(zip(df.index,map(tuple,df.values)))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM