计算与排序

 1 import pandas as pd
 2 
 3 books = pd.read_excel('Books2.xlsx')
 4 print(books.head(3))
 5 
 6 books['Price']=books['ListPrice'] * books['Discount']
 7 print(books)
 8 
 9 for i in books.index:
10     books['Price'].at[i] = books['ListPrice'].at[i] * books['Discount'].at[i]
11 print (books)
12 books.set_index('ID', inplace=True)
13 books.to_excel('Books21.xlsx')
14 print('Done!')
15 
16 books = pd.read_excel('Books2.xlsx')
17 for i in books.index:
18     books['Price'].at[i] = books['ListPrice'].at[i] * books['Discount'].at[i]
19 print (books)
20 books.set_index('ID', inplace=True)
21 # books.to_excel('Books22.xlsx')
22 # print('Done!')

排序

 1 # 排序
 2 import pandas as pd
 3 
 4 products = pd.read_excel('007/List.xlsx', index_col='ID')
 5 # ascending 为 倒置排序
 6 products.sort_values(by='Price', inplace=True, ascending=False)
 7 print(products)
 8 
 9 # 排序
10 import pandas as pd
11 
12 products = pd.read_excel('007/List.xlsx', index_col='ID')
13 products.sort_values(by=['Worthy', 'Price'], ascending=[True, False], inplace=True)
14 print(products)

数据筛选

 1 # 数据筛选
 2 import pandas as pd
 3 
 4 def age_18_to_30(a):
 5     # returen a >=18 and a< 30 和下相同,下面为python特有
 6     return 18<= a <30
 7 
 8 def level_a(s):
 9     return 85 <= s <= 100
10 
11 students = pd.read_excel('008/Students.xlsx', index_col='ID')
12 # loc为 location定位的缩写
13 # students = students.loc[students['Age'].apply(age_18_to_30)].loc[students['Score'].apply(level_a)]
14 # students = students.loc[students.Age.apply(age_18_to_30)].loc[students.Score.apply(level_a)]
15 students = students.loc[students.Age.apply(lambda a:18<= a <30)] \
16 .loc[students.Score.apply(lambda s:85 <= s <= 100)]
17 # 上述三种方法一样 空格+\ 可以换行不影响代码运行
18 print(students)

 

posted on 2019-02-21 17:40  Canvas2018  阅读(116)  评论(0)    收藏  举报