根据条件对数据框中的多行字典求和
Sum multiple rows of dictionaries in a dataframe, based on condition
如何根据具有相同隔离名称添加多个字典的值和键?
示例数据框:
Isolate
dictionary
VM20030364
{'L': 200, 'V': 500, 'T': 300, 'A': 400, 'S': 1}
VM20030364
{'L': 200, 'V': 600, 'T': 300, 'A': 450}
VM20030364
{'L': 100, 'V': 400, 'T': 300, 'A': 400, 'S': 1}
UNKNOWN-UW-1773
{'L': 500, 'V': 360, 'T': 340, 'A': 300, 'S': 1}
UNKNOWN-UW-1773
{'L': 500, 'V': 340, 'T': 340, 'A': 300, 'S': 2}
UNKNOWN-UW-1773
{'L': 500, 'V': 200, 'T': 350, 'A': 310}
输出数据帧:
Isolate
dictionary
VM20030364
{'L': 500, 'V': 1500, 'T': 900, 'A': 1250, 'S': 2}
UNKNOWN-UW-1773
{'L': 1500, 'V': 800, 'T': 1030, 'A': 910, 'S': 3}
让我们使用 Counter
映射字典列,然后使用 Isolate
group
数据框并使用 sum
进行聚合
from collections import Counter
df['dictionary'].map(Counter).groupby(df['Isolate']).sum().reset_index()
Isolate dictionary
0 UNKNOWN-UW-1773 {'L': 1500, 'V': 900, 'T': 1030, 'A': 910, 'S': 3}
1 VM20030364 {'L': 500, 'V': 1500, 'T': 900, 'A': 1250, 'S': 2}
如何根据具有相同隔离名称添加多个字典的值和键?
示例数据框:
Isolate | dictionary |
---|---|
VM20030364 | {'L': 200, 'V': 500, 'T': 300, 'A': 400, 'S': 1} |
VM20030364 | {'L': 200, 'V': 600, 'T': 300, 'A': 450} |
VM20030364 | {'L': 100, 'V': 400, 'T': 300, 'A': 400, 'S': 1} |
UNKNOWN-UW-1773 | {'L': 500, 'V': 360, 'T': 340, 'A': 300, 'S': 1} |
UNKNOWN-UW-1773 | {'L': 500, 'V': 340, 'T': 340, 'A': 300, 'S': 2} |
UNKNOWN-UW-1773 | {'L': 500, 'V': 200, 'T': 350, 'A': 310} |
输出数据帧:
Isolate | dictionary |
---|---|
VM20030364 | {'L': 500, 'V': 1500, 'T': 900, 'A': 1250, 'S': 2} |
UNKNOWN-UW-1773 | {'L': 1500, 'V': 800, 'T': 1030, 'A': 910, 'S': 3} |
让我们使用 Counter
映射字典列,然后使用 Isolate
group
数据框并使用 sum
from collections import Counter
df['dictionary'].map(Counter).groupby(df['Isolate']).sum().reset_index()
Isolate dictionary
0 UNKNOWN-UW-1773 {'L': 1500, 'V': 900, 'T': 1030, 'A': 910, 'S': 3}
1 VM20030364 {'L': 500, 'V': 1500, 'T': 900, 'A': 1250, 'S': 2}