[英]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:我想要做的是总结每个timestamp
的size
值以获得以下 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()
.str[...]
works on anything that supports __getitem__
which a dictionary does由于 ducktyping, .str[...]
适用于任何支持字典的__getitem__
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.