美文网首页
dataframe利用apply、map筛选指定的行2021-0

dataframe利用apply、map筛选指定的行2021-0

作者: 夏树的宝马 | 来源:发表于2021-06-25 10:53 被阅读0次

因为 da.loc的筛选为True的行,所以可以利用apply函数进行筛选
当然利用map函数也能达到这个效果

import pandas as pd
df=pd.DataFrame({
    "name":["给出","模拟","数据集","不妨","给定","包括","如下两列的"],
    "country":[1,2,1,2,2,3,2]
})

def single_clo(row):
    # 单列筛选
    if row==2:
        return True
    else:
        return False

def df_row(row):
    # 行筛选
    if row["country"]==2 and len(row["name"])==2:
        return True
    else:
        return False

s=df.loc[df["country"].apply(single_clo),:]
print('单列')
print(s)

print("xxxxxxxxx")
print('多列')
ss=df.apply(df_row,axis=1)
ss=df.loc[ss]
print(ss)


print("利用map")

ss=df["country"].map(lambda x:x==2)
ss_df=df.loc[ss]
print(ss_df)

结果展示

单列
    name  country
1     模拟        2
3     不妨        2
4     给定        2
6  如下两列的        2
xxxxxxxxx
多列
  name  country
1   模拟        2
3   不妨        2
4   给定        2


利用map
    name  country
1     模拟        2
3     不妨        2
4     给定        2
6  如下两列的        2

相关文章

网友评论

      本文标题:dataframe利用apply、map筛选指定的行2021-0

      本文链接:https://www.haomeiwen.com/subject/sbgnyltx.html