篩選前后數(shù)據(jù)
背景:
Pandas實現(xiàn)excel篩選數(shù)據(jù)功能饲帅,例:年齡在20歲到25歲彤钟,分數(shù)大于90分的數(shù)據(jù)
20<=Age<=25, Score>90
方法一:
DataFrame[criteria]:criteria數(shù)據(jù)篩選規(guī)則
import pandas as pd
df=pd.read_excel("D:\\python_pandas\\sample\\demo06\\Students.xlsx",index_col="ID")
#多條件篩選蚓庭,(xxx)填寫篩選條件
#AND 條件的運算符為 & ,OR 條件的運算符為 |
condition = (20<=df["Age"])&(df["Age"]<=25)&(df["Score"]>90)
data_df = df[condition]
print(data_df.head())
輸出結(jié)果:
Name Age Score
ID
6 Student_006 20 93
20 Student_020 20 94
方法二:
使用Series的apply方法主经,對一列中的每個元素執(zhí)行入?yún)⒌暮瘮?shù)
def validate_age(a):
return 20<= a <= 25
def level_b(s):
return 90 < s
data_df = df.loc[df['Age'].apply(validate_age)]\
.loc[df["Score"].apply(level_b)]
print(data_df.head())
輸出結(jié)果:
Name Age Score
ID
6 Student_006 20 93
20 Student_020 20 94