在pandas列中搜索一个值

在pandas列中搜索一个值

在这篇文章中,让我们讨论一下如何使用pandas搜索数据帧中的特定值。

用到的函数

  • where() -用于检查一个数据框的一个或多个条件,并返回相应的结果。默认情况下,不满足条件的行将被填充为NaN值。
  • dropna() -该方法允许用户分析和删除具有空值的行/列。在这篇文章中,它被用来处理这样的情况:由于不满足某个条件,行的值会变成NaN。

步骤

  • Import modules
  • Create data
  • 遍历该列,寻找一个特定的值
  • 如果匹配,选择

选择一个特定的值和选择有特定值的行之间有一个基本的区别。对于后一种情况,要检索的索引必须被存储在一个列表中。本文中包含了这两种情况的实现。

使用中的数据框架:

在pandas列中搜索一个值

例子1:选择包含工资的元组为200

import pandas as pd
x = pd.DataFrame([["A", 100, "D"], ["B", 200, "E"], ["C", 100, "F"]],
                 columns=["Name", "Salary", "Department"])
  
# Searching in whole column
for i in range(len(x.Name)):
    if 200 == x.Salary[i]:
          
        # indx will store the tuple having that 
        # particular value in column.
        indx = i
  
# below line will print that tuple
x.iloc[indx]

输出:

在pandas列中搜索一个值

例子2:搜索工资为100的人,并再次将输出存储在数据框中。

import pandas as pd
x = pd.DataFrame([["A", 100, "D"], ["B", 200, "E"], ["C", 100, "F"]], 
                 columns=[ "Name", "Salary", "Department"])
  
# initialize the indx as a list
indx = []
  
# Searching in whole column
for i in range(len(x.Name)):
    if 100 == x.Salary[i]:
        
        # indx will store all the tuples having 
        # that particular value in column.
        indx.append(i)
  
# Final Dataframe having tuples
df = pd.DataFrame()
  
# this will append all tuples to the final
# dataframe.
for indexes in indx:
    df = df.append(x.iloc[indexes])
  
df = x.where(x.Salary == 100)
  
# It will remove NaN rows.
df.dropna()

输出:

在pandas列中搜索一个值

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程