簡體   English   中英

Pandas:逗號分隔的 Excel 單元格未轉換為列表

[英]Pandas: Comma Separated Excel Cells not Converting to List

我加入了 3 個 Excel 選項卡數據集以提供我的基本數據框,然后對於每一行,我想計算 DUAlloc 中逗號分隔值中的 int 值,然后將 Amount 除以 DUAlloc 計數,然后遍歷 DuAlloc 列表並分配單獨的行,例如

基礎數據:

描述 DuAlloc 數量
廢話 1,2,3,4,5 1000
雅達 30,15,3,4,5 200

處理數據:

描述 DuAlloc 數量
廢話 1 200
廢話 2 200
廢話 3 200
雅達 3 40
廢話 4 200
雅達 4 40
廢話 5 200
雅達 5 40
雅達 15 40
雅達 30 40

我嘗試了多種轉換為列表的方法:list()、tolist(),但要么對所有計數獲得相同的數字,要么我最接近的是[len(str(c)) for c in df3['DUAlloc']]計算所有我不想要的字符。

我將如何實現這一目標,熊貓是最好的選擇嗎?

使用Series.str.splitdf.explodeGroupby.transformdf.div

In [501]: out = df.assign(DuAlloc=df['DuAlloc'].str.split(',')).explode('DuAlloc')

In [506]: out['Amount'] = out['Amount'].div(out.groupby('Description')['Amount'].transform('size'))

In [507]: out
Out[507]: 
  Description DuAlloc  Amount
0        Blah       1   200.0
0        Blah       2   200.0
0        Blah       3   200.0
0        Blah       4   200.0
0        Blah       5   200.0
1        Yada      30    40.0
1        Yada      15    40.0
1        Yada       3    40.0
1        Yada       4    40.0
1        Yada       5    40.0

您可以使用.str.count來計算,列的數量。

out = (df.assign(Amount=df['Amount'].div(df['DuAlloc'].str.count(',').add(1)),
                 DuAlloc=df['DuAlloc'].str.split(','))
       .explode('DuAlloc'))
print(out)

  Description DuAlloc  Amount
0        Blah       1   200.0
0        Blah       2   200.0
0        Blah       3   200.0
0        Blah       4   200.0
0        Blah       5   200.0
1        Yada      30    40.0
1        Yada      15    40.0
1        Yada       3    40.0
1        Yada       4    40.0
1        Yada       5    40.0

暫無
暫無

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

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