简体   繁体   English

Python:如何对列中字典列表的值求和

[英]Python: How to sum up the values of a dictionary list in a column

I have a DataFrame like this:我有一个这样的 DataFrame:

timestamp                                asks
2022-01-01 00:00:00                 [{'price':'0.99', 'size':'12311'},{'price':'0.991', 'size':'20013'}]
2022-01-01 01:00:00                 [{'price':'0.99', 'size':'3122'},{'price':'0.991', 'size':'43221'}]
...

What I want to do is sum up the values of size for each timestamp to get the following DataFrame:我想要做的是总结每个timestampsize值以获得以下 DataFrame:

timestamp                 asks
2022-01-01 00:00:00       32324
2022-01-01 01:00:00       46343
...

ie 12311+20013= 32324 .12311+20013= 32324

How can this be done (using pandas ideally)?如何做到这一点(理想情况下使用 pandas)?

df["asks"] = df["asks"].explode().str["size"].astype(int).groupby(level=0).sum()
  • get each dictionary on a separate row将每个字典放在单独的行中
  • get the "size" key's value for each of them获取每个键的“大小”键值
    • due to ducktyping, .str[...] works on anything that supports __getitem__ which a dictionary does由于 ducktyping, .str[...]适用于任何支持字典的__getitem__
  • convert to integers and unexplode转换为整数并展开

to get要得到

>>> df

             timestamp   asks
0  2022-01-01 00:00:00  32324
1  2022-01-01 01:00:00  46343

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM