![](/img/trans.png)
[英]Converting list to comma separated integers to be substituted in IN clause of Pandas dataframe query
[英]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.split
、 df.explode
、 Groupby.transform
和df.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.