任务6: 函数填充
首先定义一个DataFrame “books”,并导入现有excel文件Books.xlsx
books = pd.read_excel('C:/Temp/Books.xlsx', index_col='ID')
根据Price = ListPrice * Discount这个公式。用代码可以表示为:
books['Price'] = books['ListPrice'] * books['Discount']
注:以上代码显示该计算是发生在books['Price'],books['ListPrice']和books['Discount']三个Series里面。即是列与列的运算,速度快效率高。
打印后结果
Name ListPrice Discount Price
ID
1 Book_001 10 0.5 5.0
2 Book_002 20 0.5 10.0
3 Book_003 30 0.5 15.0
4 Book_004 40 0.5 20.0
5 Book_005 50 0.5 25.0
6 Book_006 60 0.5 30.0
7 Book_007 70 0.5 35.0
8 Book_008 80 0.5 40.0
9 Book_009 90 0.5 45.0
10 Book_010 100 0.5 50.0
11 Book_011 110 0.5 55.0
12 Book_012 120 0.5 60.0
13 Book_013 130 0.5 65.0
14 Book_014 140 0.5 70.0
15 Book_015 150 0.5 75.0
16 Book_016 160 0.5 80.0
17 Book_017 170 0.5 85.0
18 Book_018 180 0.5 90.0
19 Book_019 190 0.5 95.0
20 Book_020 200 0.5 100.0
如果想要实现一行一行(类似excel里的算法)的计算可以通过一个for循环:
for i in books.index:
books['Price'].at[i]=books['ListPrice'].at[i]*books['Discount'].at[i]
如果要指定某几行的计算可以使用range()
如计算第5到第16行:
for i in range(5,16):
books['Price'].at[i]=books['ListPrice'].at[i]*books['Discount'].at[i]
如果想对某一列(Series)进行加减运算,可以通过赋值的方法
如给ListPrice 上加2:
books['ListPrice'] = books['ListPrice'] + 2
或者使用Series的Series.apply()方法:
books['ListPrice'] = books['ListPrice'].apply(add_2)
注:add_2为自定义的一个函数
def add_2(x):
return x + 2
输出结果:
Name ListPrice Discount Price
ID
1 Book_001 12 0.5 5.0
2 Book_002 22 0.5 10.0
3 Book_003 32 0.5 15.0
4 Book_004 42 0.5 20.0
5 Book_005 52 0.5 25.0
6 Book_006 62 0.5 30.0
7 Book_007 72 0.5 35.0
8 Book_008 82 0.5 40.0
9 Book_009 92 0.5 45.0
10 Book_010 102 0.5 50.0
11 Book_011 112 0.5 55.0
12 Book_012 122 0.5 60.0
13 Book_013 132 0.5 65.0
14 Book_014 142 0.5 70.0
15 Book_015 152 0.5 75.0
16 Book_016 162 0.5 80.0
17 Book_017 172 0.5 85.0
18 Book_018 182 0.5 90.0
19 Book_019 192 0.5 95.0
20 Book_020 202 0.5 100.0
本节课代码:
import pandas as pd
def add_2(x):
return x + 2
books = pd.read_excel('C:/Temp/Books.xlsx', index_col='ID')
books['Price'] = books['ListPrice'] * books['Discount']
# for i in books.index:
# for i in range(5,16):
# books['Price'].at[i]=books['ListPrice'].at[i]*books['Discount'].at[i]
#books['ListPrice'] = books['ListPrice'] + 2
books['ListPrice'] = books['ListPrice'].apply(add_2)
print(books)