![](/img/trans.png)
[英]How can I split the difference between two timestamps that contain more than one hour in a Pandas DataFrame
[英]How can I create a dictionary between two columns within a pandas dataframe if each column has more than one value per row?
我有一個 Pandas 數據框,列的格式與下面類似:
test_df = pd.DataFrame(
{'A': ['apples|oranges|bananas', 'apples|oranges', 'apples|kiwi'],
'B': ['store1|store2|store3', 'store1|store2', 'store1|store4']})
A B
apples|oranges|bananas store1|store2|store3
apples|oranges store1|store2
apples|kiwi store1|store4
每列的索引以“|”分隔一切順利。 除了數據幀中每行的當前項目排序之外,沒有關於哪種水果適合哪個商店的鍵。 我想為具有所需輸出的每一行創建一個帶有字典的新列:
A B C
apples|oranges|bananas store1|store2|store3 {store1:apples, store2:oranges, store3:bananas}
apples|oranges store1|store2 {store1:apples, store2:oranges}
apples|kiwi store1|store4 {store1:apples, store4:kiwi}
首先,我嘗試將 A 列和 B 列轉換為列表並將它們轉換為字典。
test_df.A = test_df.A.str.split('|').tolist()
test_df.B = test_df.B.str.split('|').tolist()
我嘗試了幾種不同的將列表轉換為字典的方法:
test_df['C'] = dict(zip(test_df.A,test_df.B))
不起作用並導致“TypeError: 'dict' object is not callable”錯誤。
test_df.groupby('A')['B'].apply(list).to_dict()
不起作用並導致 'unhashable type:'list' 錯誤,我認為這是因為 'B' 中的字典鍵有多個值。
我能做些什么來解決這個問題?
如果您真的需要維護該組織,您可以通過(慢速)應用程序在您首先拆分字符串、壓縮結果列表並生成 dict 的地方獲得:
test_df['C'] = test_df.apply(lambda r: dict(zip(r.B.split('|'), r.A.split('|'))), axis=1)
A B C
0 apples|oranges|bananas store1|store2|store3 {'store1': 'apples', 'store2': 'oranges', 'store3': 'bananas'}
1 apples|oranges store1|store2 {'store1': 'apples', 'store2': 'oranges'}
2 apples|kiwi store1|store4 {'store1': 'apples', 'store4': 'kiwi'}
因為字典必須有唯一的鍵,如果B
中的存儲在同一行上重復,請將dict
更改為tuple
,這樣您就可以存儲所有內容。
但是,您可以使用explode
獲得類似的組織。 由於這會以一種扁平的方式來存儲您的所有數據,因此未來的操作將變得更加容易和高效。 因為我們分解了列,索引被復制並讓您知道它來自哪一行。
test_df = pd.concat([test_df[col].str.split('|').explode() for col in test_df.columns], 1)
A B
0 apples store1
0 oranges store2
0 bananas store3
1 apples store1
1 oranges store2
2 apples store1
2 kiwi store4
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.