![](/img/trans.png)
[英]python pandas: Check if dataframe's column value is in another dataframe's column, then count and list it
[英]Python Add Column to Pandas Dataframe That is a Count of List Elements in Another Column
我使用pymongo API從MongoDB數據庫中提取數據並將其插入到pandas數據幀中。 數據庫中的某些字段包含診斷代碼列表。 其中大多數都有一個伴隨的“計數”字段,但其中一個沒有。 對於我計划定期對此數據執行的分析,此計數非常重要。 數據幀“DF”如下所示:
dxCodes memberID newDx
0 [4280, 4293, 4241, 4240, 4242, 4243] 856589080 0
1 [V7612] 906903383 0
2 [4550, 4553, V1582] 837210554 0
3 [78791, 28860, V1582, 496, 25000, 4019] 935634391 0
4 [30500, 42731, 4280, 496, 59972, 4019, 3051] 929185103 0
我需要在其中創建一個新列,其中包含診斷代碼字段中包含的診斷代碼的計數。 我一直在互聯網上,但我嘗試過的解決方案都沒有成功。 我得到的最接近的是這個
DF['dxCount'] = len(DF['dxCodes'])
但是,我得到了這個結果
dxCodes memberID newDx dxCount
0 [4280, 4293, 4241, 4240, 4242, 4243] 856589080 0 139360
1 [V7612] 906903383 0 139360
2 [4550, 4553, V1582] 837210554 0 139360
3 [78791, 28860, V1582, 496, 25000, 4019] 935634391 0 139360
4 [30500, 42731, 4280, 496, 59972, 4019, 3051] 929185103 0 139360
dxCount列中顯示的數字是數據幀中的行數,但我希望它顯示dxCodes字段中的dx代碼數,因此所需的結果將是
dxCodes memberID newDx dxCount
0 [4280, 4293, 4241, 4240, 4242, 4243] 856589080 0 6
1 [V7612] 906903383 0 1
2 [4550, 4553, V1582] 837210554 0 3
3 [78791, 28860, V1582, 496, 25000, 4019] 935634391 0 6
4 [30500, 42731, 4280, 496, 59972, 4019, 3051] 929185103 0 7
我的Python旅程已經走了很長一段路,但是這一次讓我在多天的時間里撞到牆上幾個小時。 提前感謝你的幫助!
列表理解應該在這里工作:
>>> df['dxCount'] = [len(c) for c in df['dxCodes']]
雖然更好的設計可能是將dxCodes
在由memberID
索引的單獨數據幀中,以便它們可以存儲為同源字符串列。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.