通过列值过滤Pandas DataFrame的方法
在这篇文章中,我们将看到通过列值过滤Pandas Dataframe的不同方法。首先,让我们创建一个Dataframe。
# importing pandas
import pandas as pd
# declare a dictionary
record = {
'Name' : ['Ankit', 'Swapnil', 'Aishwarya',
'Priyanka', 'Shivangi', 'Shaurya' ],
'Age' : [22, 20, 21, 19, 18, 22],
'Stream' : ['Math', 'Commerce', 'Science',
'Math', 'Math', 'Science'],
'Percentage' : [90, 90, 96, 75, 70, 80] }
# create a dataframe
dataframe = pd.DataFrame(record,
columns = ['Name', 'Age',
'Stream', 'Percentage'])
# show the Dataframe
print("Given Dataframe :\n", dataframe)
输出:
方法1:使用’>’、’=’、’=’、'<=’、’!=’操作符,根据特定的列值选择Pandas数据框架的行。
实例1:使用[ ]从给定的数据框架中选择 “百分比 “大于75的所有行。
# selecting rows based on condition
rslt_df = dataframe[dataframe['Percentage'] > 70]
print('\nResult dataframe :\n', rslt_df)
输出:
示例2:使用 loc[ ],从给定的数据框架中选择所有 “百分比 “大于70的行。
# selecting rows based on condition
rslt_df = dataframe.loc[dataframe['Percentage'] > 70]
print('\nResult dataframe :\n',
rslt_df)
输出:
方法2:使用数据框架的isin()方法选择那些列值出现在列表中的Pandas数据框架的行。
示例1:从给定的数据框架中选择所有的行,其中’流’在选项列表中出现,使用[ ]。
options = ['Science', 'Commerce']
# selecting rows based on condition
rslt_df = dataframe[dataframe['Stream'].isin(options)]
print('\nResult dataframe :\n',
rslt_df)
输出:
示例2:使用loc[ ]从给定的数据框架中选择所有的行,其中’Stream’出现在选项列表中。
options = ['Science', 'Commerce']
# selecting rows based on condition
rslt_df = dataframe.loc[dataframe['Stream'].isin(options)]
print('\nResult dataframe :\n',
rslt_df)
输出:
方法3:使用’&’操作符,根据多列条件选择Pandas数据框架的行。
例子1:从给定的数据框架中选择所有行,其中’年龄’等于22,’流’出现在选项列表中,使用[ ]。
options = ['Commerce' ,'Science']
# selecting rows based on condition
rslt_df = dataframe[(dataframe['Age'] == 22) &
dataframe['Stream'].isin(options)]
print('\nResult dataframe :\n',
rslt_df)
输出:
例子2:使用loc[ ]从给定的数据框架中选择所有行,其中’年龄’等于22,’流’出现在选项列表中。
options = ['Commerce', 'Science']
# selecting rows based on condition
rslt_df = dataframe.loc[(dataframe['Age'] == 22) &
dataframe['Stream'].isin(options)]
print('\nResult dataframe :\n',
rslt_df)
输出: