编写一个 Python 函数,它接受 DataFrame Age、Salary 列的第二、第三和第四行作为输入,并找到平均值和值的乘积
输入-
假设,样本数据帧是,
Id Age salary 0 1 27 40000 1 2 22 25000 2 3 25 40000 3 4 23 35000 4 5 24 30000 5 6 32 30000 6 7 30 50000 7 8 28 20000 8 9 29 32000 9 10 27 23000
输出-
给定切片行的平均值和乘积的结果是,
mean is Age 23.333333 salary 33333.333333 product is Age 12650 salary 35000000000000
解决方案
为了解决这个问题,我们将遵循以下方法。
定义数据帧
创建一个函数,使用iloc函数对第二、第三和第四行age和salary列进行切片,并将其存储在结果DataFrame中。
df.iloc[1:4,1:]
从结果DataFrame计算均值和乘积。
例子
让我们看看下面的实现,以便更好地理解。
import pandas as pd
def find_mean_prod():
data = [[1,27,40000],[2,22,25000],[3,25,40000],[4,23,35000],[5,24,30000], [6,32,30000],[7,30,50000],[8,28,20000],[9,29,32000],[10,27,23000]]
df = pd.DataFrame(data,columns=('Id','Age','salary'))
print(df)
print("slicing second,third and fourth rows of age and salary columns\n")
result = df.iloc[1:4,1:]
print("mean is\n", result.mean())
print("product is\n", result.prod())
find_mean_prod()输出
Id Age salary 0 1 27 40000 1 2 22 25000 2 3 25 40000 3 4 23 35000 4 5 24 30000 5 6 32 30000 6 7 30 50000 7 8 28 20000 8 9 29 32000 9 10 27 23000 slicing second,third and fourth rows of age and salary columns mean is Age 23.333333 salary 33333.333333 product is Age 12650 salary 35000000000000
热门推荐
5 简短元宵节祝福语
10 生日奶茶红包祝福语简短
11 吃饭后祝福语2026简短
12 老人去世简短祝福语
13 留学生祝福语简短
14 爸爸寿宴仪式祝福语简短
15 五一快乐祝福语简短老师
16 中秋祝福语简短女朋友
17 英语祝福语大全简短母亲
18 毕业女孩祝福语简短独特