我有这样的数组:
array = [['page', 'pageviews'],
['page1', '65'],
['page2', '44'],
['page1', '40']]
如何使脚本遍历行并使用'page1'进行一行处理,并将两个值'65'和'40'求和。
最佳答案
这是使用pandas
的解决方案:
import pandas as pd
# read list of lists into pandas dataframe
df = pd.DataFrame(array[1:], columns=array[0])
# convert views from string to integer
df['pageviews'] = df['pageviews'].astype(int)
# group by page, sum pageviews, create list from results
lst = df.groupby('page')['pageviews'].sum()\
.reset_index().values.tolist()
# add headers
res = [array[0]] + lst
print(res)
[['page', 'pageviews'],
['page1', 105],
['page2', 44]]