簡體   English   中英

將 Python dataframe 轉換為帶索引的字典

[英]Convert Python dataframe to dictionary with index

我正在嘗試將 dataframe 轉換為字典(因為它們在過濾鍵時更快)我目前正在使用

t3 = time()
r={}
for i in df.index.unique():
    r[i]=[]
    r[i].append(df.loc[i].values)
print(round((time()-t3), 1), "s")

這種類型的轉換很慢。 有沒有替代方案? 我希望 dataframe 的索引作為鍵和行作為在單個鍵上具有多個值的值

轉置后使用pandas.DataFrame.to_dict以獲取索引作為鍵和行值作為值:

import pandas as pd

df = pd.DataFrame({'col1': [1, 2], 'col2': ['a', 'b']})
r = df.T.to_dict('list')
print(r)

Output:

{0: [1, 'a'], 1: [2, 'b']}

我能夠使用以下方法將具有多個重復索引的 dataframe 轉換為字典:

dicti={}
for line in df.itertuples():
   if line.index not in dicti:
      dicti[line.index]=[]
      dicti[line.index].append(list(line))
   else:
      dicti[line.index].append(list(line))

600k 行的運行時間為 5 秒

暫無
暫無

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

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