簡體   English   中英

Pandas,將csv文件讀入字典

[英]Pandas, read csv file into dictionary

有沒有一種方法可以在字典中讀取 CSV 文件,以便元組中的自定義行是鍵,而 rest (元組中)是值?

這是一個示例表:

A |B |C |D |E
--------------
0 |0 |0 |5 |1
0 |1 |0 |2 |8
1 |0 |0 |5 |7
1 |1 |0 |3 |7
0 |0 |1 |9 |0

結果:

dictionary[(A,B,C)] = (D, E)
print(dictionary[(0,0,0)]) # (5,1)

有沒有一種有效的方法來實現這一目標?

考慮到 pandas dataframe df

 A  B  C  D  E
 0  0  0  5  1
 0  1  0  2  8
 1  0  0  5  7
 1  1  0  3  7
 0  0  1  9  0

讓我們將zipA, B, CD, E放在一起,並在 dict 理解中制作元組的鍵值對:

k, v = ['A', 'B', 'C'], ['D', 'E']
dct = {tuple(x): tuple(y) for x, y in zip(df[k].to_numpy(), df[v].to_numpy())}

結果:

{(0, 0, 0): (5, 1),
 (0, 1, 0): (2, 8),
 (1, 0, 0): (5, 7),
 (1, 1, 0): (3, 7),
 (0, 0, 1): (9, 0)}

我不確定這是否是最好的解決方案,但它有效:

pd.concat([df[['A', 'B', 'C']].apply(tuple, 1),
           df[['D', 'E']].apply(tuple, 1)], axis=1)\
  .set_index(0)[1].to_dict()
#{(0, 0, 0): (5, 1), (0, 1, 0): (2, 8), (1, 0, 0): (5, 7), 
# (1, 1, 0): (3, 7), (0, 0, 1): (9, 0)}

暫無
暫無

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

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