簡體   English   中英

從 dict 創建數據框時防止 Pandas 解包元組

[英]Prevent Pandas from unpacking a tuple when creating a dataframe from dict

從字典創建 Pandas 中的 DataFrame 時,會自動展開一個元組,即

import pandas
d = {'a': 1, 'b': 2, 'c': (3,4)}
df = pandas.DataFrame.from_dict(d)
print(df)

回報

   a  b  c
0  1  2  3
1  1  2  4

除了先將元組轉換為字符串之外,還有什么辦法可以防止這種情況發生嗎? 我希望結果是

   a  b  c
0  1  2  (3, 4)

嘗試添加[] ,因此具有鍵cdictionary中的值是tuple list

import pandas

d = {'a': 1, 'b': 2, 'c': [(3,4)]}
df = pandas.DataFrame.from_dict(d)

print(df)
   a  b       c
0  1  2  (3, 4)

傳遞參數orient='index'並轉置結果,這樣它就不會廣播標量值:

In [13]:
d = {'a': 1, 'b': 2, 'c': (3,4)}
df = pd.DataFrame.from_dict(d, orient='index').T
df

Out[13]:
   a       c  b
0  1  (3, 4)  2

要處理第一個 dict 條目是元組的情況,您需要將所有 dict 值包含在一個列表中,以便它是可迭代的:

In [20]:
d = {'a': (5,6), 'b': 2, 'c': 1}
d1 = dict(zip(d.keys(), [[x] for x in d.values()]))
pd.DataFrame.from_dict(d1, orient='index').T

Out[23]:
        a  b  c
0  (5, 6)  2  1

暫無
暫無

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

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