簡體   English   中英

使用 pandas 計算 excel 表中特定行的總和

[英]calculating sum of specific rows in excel sheet using pandas

嗨 :) 我是 python 的新手,想尋求幫助以計算 excel 工作表中特定行的總和。 我嘗試過在線搜索幫助,但是給出的所有示例都與我的情況不同,所以我發現很難根據我的需要修改代碼。 這是我使用的代碼。 (需要計算表格中特定國家/地區的行內值的總和)

import pandas as pd

df = pd.read_excel(r'C:\Users\julia\OneDrive\Documents\python assignment\2016 data -EU 
values.xlsx', sheet_name='PM10 ')
for row in plot.iterrows():
    if 'Country' == 'Malta':
      sum_pollution = plot['AirPollutionLevel'].sum()
    print()

對於上下文,excel 表看起來像這樣鏈接到圖片

任何幫助將不勝感激!

你可以這樣做:

df[df["country"] == "Malta"]["AirPollutionLevel"].sum()

上面代碼中的步驟:

  • 抓取國家等於馬耳他的所有行
  • 抓住這個子集的 AirPollutionLevel 列
  • 總結一下!

如果你想使用iterrows()你可以這樣做:
編輯:添加skiprows ,因為您的真實數據從第 7 行開始

import pandas as pd

df = pd.read_excel(r'C:\Users\julia\OneDrive\Documents\python assignment\2016 data -EU 
values.xlsx', sheet_name='PM10 ', skiprows=6)

result = 0

for row in df.iterrows():
    if row[1]['Country'] == 'Malta':
        result += row[1]['AirPollutionLevel']

print(result)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM