Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

หาผลรวมแต่ละแถวใน Pandas DataFrame ด้วย sum(axis=1)

แนวคิด

เมธอด DataFrame.sum(axis=1) คำนวณผลรวมแนวนอน (row-wise) คืน Series ที่ index เดิม ค่าคือผลรวมของแต่ละแถว

ตัวอย่างโค้ด

import pandas as pd

df = pd.DataFrame({
    "Opening_Stock": [300, 700, 1200, 1500],
    "Closing_Stock": [200, 500, 1000, 900]
})

print("DataFrame:\n", df)

# ผลรวมแต่ละแถว
row_sums = df.sum(axis=1)
print("\nผลรวมแต่ละแถว:\n", row_sums)

ผลลัพธ์

DataFrame:
   Closing_Stock  Opening_Stock
0            200            300
1            500            700
2           1000           1200
3            900           1500

ผลรวมแต่ละแถว:
0     500
1    1200
2    2200
3    2400
dtype: int64

รายละเอียด axis

axisทิศทางผลลัพธ์
0 (default)แนวตั้ง (column-wise)ผลรวมแต่ละคอลัมน์ (Series index = column names)
1แนวนอน (row-wise)ผลรวมแต่ละแถว (Series index = row index)

การประยุกต์

# เพิ่มเป็นคอลัมน์ใหม่
df['Total_Stock'] = df.sum(axis=1)

# กรองแถวที่ผลรวม > threshold
df[df.sum(axis=1) > 1000]

# ใช้กับคอลัมน์เฉพาะ
df[['Opening_Stock', 'Closing_Stock']].sum(axis=1)