import functools
import pandas as pd
import numpy as np
df = pd.read_excel("examples.xls")
# review what learned yesterday
df["level"] = np.where(df.年级 <= 2013, "old", "new")
df.to_excel("example_new.xls")
# spliting
# select the index satisfy some condition
df_new = df.loc[df.年级 > 2013]
# Building Criteria
# 选择满足多个条件的行, 这其实也是昨天的内容
df_new = df[(df.年级 == 2013) & (df.是否在职生 == 0)]
# 根据条件修改某列
df.loc[(df.年级 == 2013) | (df.学习形式代码 == 1), "注册状态"] = 1
# 根据条件增加某列
df["满足条件"] = np.where((df.年级 == 2013) | (df.学习形式代码 == 1), "是", "否")
# 根据条件进行排序
df2 = pd.DataFrame({'AAA': [4,5,6,7], 'BBB': [10,20,30,40], 'CCC': [100,50,-30,-50]})
df2_sort = df2.loc[(df2.AAA-5.5).abs().argsort()]
df2_sort2 = df2.loc[(df2.AAA-5.5).argsort()]
a = df2.AAA # 这得到的是一个Series
print(df2_sort2)
# 多个条件选择
Crit1 = df2.AAA <= 5.5
Crit2 = df2.BBB == 10
Crit3 = df2.CCC > -40.0
CritList = [Crit1, Crit2, Crit3]
AllCrit = functools.reduce(lambda x, y: x & y, CritList) # reduce: x&y&z
print(df2.loc[AllCrit])
今天的很多知识都是昨天提到过的,仅增加两个知识点:
1. 根据某一列排序更快的写法: df.loc[df.AAA.argsort()] #事实上这就是用argsort()函数先生成一个index的array
2. 根据多个条件筛选,更快的写法:
df.loc[functools.reduce(lambda x, y: x & y, CritList)]
# lambda x, y: x & y是一个整体,作为一个function
# CritList作为sequence
# 对于reduce的解释:For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates
((((1+2)+3)+4)+5)
代码在https://github.com/zhangjipinggom/pandas_learning
其他记录:
(1)通过循环的方式添加某一列
def filter(df, target1, category_name1, target2, category_name2, xls_name):
fangxiangma = []
for course0 in df.业务课二代码.values:
if course0 in target1:
fangxiangma.append(category_name1)
elif course0 in target2:
fangxiangma.append(category_name2)
else:
fangxiangma.append(0)
df["方向码"] = fangxiangma
df.to_excel("added"+xls_name)
(2)在组内排序
比如在同一个"方向码"内按照"总成绩"排序
df.sort_values(['方向码','总成绩'], ascending = [True,False], inplace=True)