Pandas 列求和操作

Pandas 列求和操作

在本文中,我们将介绍如何使用Pandas库来对Pandas DataFrame中列数据进行求和操作。

阅读更多:Pandas 教程

创建示例DataFrame

我们先创建一个示例DataFrame,包含三列数据:品牌、销售量和销售价格。

import pandas as pd

data = {
    'Brand': ['Apple', 'Samsung', 'Huawei', 'Xiaomi'],
    'Sales Volume': [1000, 2000, 1500, 800],
    'Sales Price': [9999, 7999, 6999, 4999]
}
df = pd.DataFrame(data)
print(df)

输出结果如下:

     Brand  Sales Volume  Sales Price
0    Apple          1000         9999
1  Samsung          2000         7999
2   Huawei          1500         6999
3   Xiaomi           800         4999

使用sum()方法求和

Pandas库提供了sum()方法来对列数据进行求和。我们可以针对单个列进行求和,也可以对多个列同时求和。

针对单个列求和

sales_volume_sum = df['Sales Volume'].sum()
print(sales_volume_sum)

输出结果为:

5300

针对多个列求和

total_sales = df.sum(numeric_only=True)
print(total_sales)

numeric_only=True表示只对数值型数据求和。输出结果为:

Sales Volume     5300
Sales Price     29996
dtype: int64

使用apply()方法求和

除了sum()方法外,还可以使用apply()方法对列数据进行求和。apply()方法可以接收一个函数作为参数,用于对行或列进行操作。

针对单个列求和

sales_price_sum = df['Sales Price'].apply(lambda x: x).sum()
print(sales_price_sum)

输出结果为:

29996

针对多个列求和

total_sales2 = df.apply(lambda x: x.sum() if x.dtype == 'int64' else x.sum(skipna=False))
print(total_sales2)

输出结果为:

Brand           AppleSamsungHuaweiXiaomi
Sales Volume                       5300
Sales Price                       29996
dtype: object

使用numpy库来求和

除了使用Pandas库自带的sum()和apply()方法,还可以使用numpy库来对数据进行求和。

import numpy as np

sales_volume = df['Sales Volume'].to_numpy()
sales_volume_sum2 = np.sum(sales_volume)
print(sales_volume_sum2)

输出结果和之前使用sum()方法得到的一样:

5300

总结

本文介绍了如何使用Pandas库来对DataFrame中的列数据进行求和操作。我们可以使用sum()方法、apply()方法和numpy库来求和,对单列和多列进行操作。在实际数据处理中,对数据进行合理的求和是非常重要的,有助于我们理解数据的总体情况。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程