对Python数据帧中的列求和

2024-06-16 09:53:42 发布

您现在位置:Python中文网/ 问答频道 /正文

这张来自维基百科的表格显示了10大票房。我似乎无法得到“全球总量”一栏的总数。有人能帮忙吗?多谢各位

import pandas as pd
boxoffice_df=pd.read_html('https://en.wikipedia.org/wiki/List_of_highest-grossing_films')
films = boxoffice_df[1]

films.rename(columns = {'Worldwide gross(2020 $)':'worldwide_gross'}, inplace = True)

films.worldwide_gross.sum(axis=0)

enter image description here

这是我在计算全球总收益时得到的结果: enter image description here


Tags: importpandasdfreadasworldwide表格全球
3条回答
films.astype({"worldwide_gross": int})    
Total =films['worldwide_gross'].sum()

您只需使用regex在列中保留数字,然后使用series.astype('float')将列转换为浮点

加:

films.worldwide_gross = films.worldwide_gross.str.replace('\D',"",regex = True).astype(float)

完整代码:

import pandas as pd
boxoffice_df=pd.read_html('https://en.wikipedia.org/wiki/List_of_highest-grossing_films')
films = boxoffice_df[1]

films.rename(columns = {'Worldwide gross(2020 $)':'worldwide_gross'}, inplace = True)
films.worldwide_gross = films.worldwide_gross.str.replace('\D',"",regex = True).astype(float)
films.worldwide_gross.sum(axis=0)
Total =films['worldwide_gross'].astype('Int32').sum()

或者先转换数据类型

films = films.convert_dtypes()
Total = films['worldwide_gross'].sum()

相关问题 更多 >