如何使用for循环过滤熊猫数据框中的观测值?

时间:2019-09-13 00:26:41

标签: python pandas loops for-loop subset

我有一个熊猫数据框,其中有我感兴趣的三列(城市,国家和运动队)。我想在“国家=意大利”和“运动队=足球”的地方进行过滤,然后打印出符合该条件的城市。它必须在for循环中完成...

我尝试过:

for i,a in mydf.iterrows():
    if mydf['Country'][i] == "Italy":
    if mydf['Sports Team'][a] == "Soccer":
    Print('City')

它说:系列的真值是模棱两可的。使用a.empty,a.bool(),a.item(),a.any()或a.all()。

3 个答案:

答案 0 :(得分:0)

尝试:

    mydf[(mydf['Country'] == 'Italy')&(mydf['Sports Team'] == 'Soccer')]['City']

这应该为您提供符合条件的城市的DataFrame列。

答案 1 :(得分:0)

有多种方法可以过滤熊猫数据框,但是由于您使用的是iterrows(),因此我已经回答过了,

import pandas as pd

# create the dataframe
my_data = [{
            'Country': 'Italy',
            'City': 'City 1',
            'Sports Team': 'Soccer'
        },
        {
            'Country': 'Italy',
            'City': 'City 2',
            'Sports Team': 'Soccer'
        }]

mydf = pd.DataFrame(my_data)

for index, row in mydf.iterrows():
    if row['Country'] == 'Italy' and row['Sports Team'] == 'Soccer':
        print(row['City'])

mydf看起来像

   City     Country    Sports Team
0  City 1   Italy      Soccer
1  City 2   Italy      Soccer

输出将是

City 1
City 2

答案 2 :(得分:0)

尝试..

最好使用.loc和.iloc

DataFrame示例:

>>> mydf
     City Country Sports Team
0  City 1   Italy      Soccer
1  City 2   Italy      Soccer
2  City 3   Spain      Soccer
3  City 4  Brazil    Football
4  City 2   Italy    Football

结果:

>>> mydf.loc[(mydf['Country'] == 'Italy') &  (mydf['Sports Team'] == 'Soccer')]['City']
0    City 1
1    City 2
Name: City, dtype: object