Python - 基于列值在 Pandas 中使用查询功能过滤行?
要根据列值过滤行,我们可以使用该query()函数。在函数中,设置过滤记录的条件。首先,导入所需的库-
import pandas as pd
以下是我们的团队记录数据-
Team = [['India', 1, 100],['Australia', 2, 85],['England', 3, 75],['New Zealand', 4 , 65],['South Africa', 5, 50],['Bangladesh', 6, 40]]
从上面创建一个DataFrame并添加列-
dataFrame = pd.DataFrame(Team, columns=['Country', 'Rank', 'Points'])
使用query()与“等级”筛选记录为5-
dataFrame.query("Rank == 5"))
示例
以下是完整的代码-
import pandas as pd #以团队排名列表形式的数据 Team = [['India', 1, 100],['Australia', 2, 85],['England', 3, 75],['New Zealand', 4 , 65],['South Africa', 5, 50],['Bangladesh', 6, 40]] #创建DataFrame并添加列 dataFrame = pd.DataFrame(Team, columns=['Country', 'Rank', 'Points']) print"DataFrame...\n",dataFrame #使用查询过滤行 print"\nFetch Team with Rank 5..\n",dataFrame.query("Rank == 5")输出结果
这将产生以下输出-
DataFrame... Country Rank Points 0 India 1 100 1 Australia 2 85 2 England 3 75 3 New Zealand 4 65 4 South Africa 5 50 5 Bangladesh 6 40 Fetch Team with Rank 5.. Country Rank Points 4 South Africa 5 50
示例
让我们再看一个例子。在这里,我们有一个不同的条件来过滤行-
import pandas as pd #以团队排名列表形式的数据 Team = [['India', 1, 100],['Australia', 2, 85],['England', 3, 75],['New Zealand', 4 , 65],['South Africa', 5, 50],['Bangladesh', 6, 40]] #创建DataFrame并添加列 dataFrame = pd.DataFrame(Team, columns=['Country', 'Rank', 'Points']) print"DataFrame...\n",dataFrame #使用查询过滤行 print"\nFetch Team with points above 70 and Rank less than 3..\n" print(dataFrame.query("Points > 70 and Rank <3"))输出结果
这将产生以下输出-
DataFrame... Country Rank Points 0 India 1 100 1 Australia 2 85 2 England 3 75 3 New Zealand 4 65 4 South Africa 5 50 5 Bangladesh 6 40 Fetch Team with points above 70 and Rank less than 3.. Country Rank Points 0 India 1 100 1 Australia 2 85