Python 对整数执行条件检查时出错

Python 对整数执行条件检查时出错,python,pandas,Python,Pandas,我有一个数据框,我想对它做一些操作。基本上,我试图实现的是访问其中一列,并将其用作流程中其他操作的输入值 我需要做的第一件事是访问给定的列值并进行逻辑检查。但即使那一步我的条件掉了一部分 以下是数据和函数: import pandas as pd raw_data = {'first_name': ['Jason', 'Molly', 'Marie', 'Kerie', np.nan], 'nationality': ['USA', 'USA', 'France', 'UK',

我有一个数据框,我想对它做一些操作。基本上,我试图实现的是访问其中一列,并将其用作流程中其他操作的输入值

我需要做的第一件事是访问给定的列值并进行逻辑检查。但即使那一步我的条件掉了一部分

以下是数据和函数:

import pandas as pd
raw_data = {'first_name': ['Jason', 'Molly', 'Marie', 'Kerie', np.nan], 
        'nationality': ['USA', 'USA', 'France', 'UK', 'UK'], 
        'age': [42, 52, 36, 24, 70]}
df = pd.DataFrame(raw_data, columns = ['first_name', 'nationality', 'age'])

      first_name nationality  age
    0      Jason         USA   42
    1      Molly         USA   52
    2      Marie      France   36
    3      Kerie          UK   24
    4        NaN          UK   70

person_filter = ['Jason', 'Kerie','Marie']



def process_data(df):

    for pf in person_filter:

        df1 = df.drop_duplicates(subset = ['nationality'],keep='first')
        age=df1[df1.first_name==pf][['age']].astype(str).astype(int)

        print(age)
        print(age.dtypes)
        for ag in age:

            if ag < 30:

                #will use ag as input to do some special op

                print('you are young')
            else:
                #will use ag as input to do some special op

                print('you are older')




print(process_data(df))
TypeError:“问题在于ag变量是列名而不是值。要获取值,只需调用age变量上的.values:

age.values
简而言之,将ag In age替换为:by for ag In age.values:然后从列表中选择第一个元素

这里有一个例子:

def process_data(df):
    for pf in person_filter:
        df1 = df.drop_duplicates(subset = ['nationality'],keep='first')
        age=df1[df1.first_name==pf][['age']].astype(str).astype(int)
        for ag in age.values:
            if ag[0] < 30:
                #will use ag as input to do some special op
                print('you are young ({} years)'.format(ag[0]))
            else:
                print("you are old ({} years)".format(ag[0]))
                #will use ag as input to do some special op

process_data(df)
# you are old(42 years)
# you are young(24 years)
# you are old(36 years)
替换以下行

for ag in age:


ag是当前列名。欢迎使用StackOverflow。看见在您发布MRE代码并准确说明问题之前,我们无法有效地帮助您。我们应该能够将您发布的代码粘贴到文本文件中,并重现您指定的问题。您的代码既不是最小的,也不是给定的可执行代码。@AlexandreB。是的,我需要访问年龄列值。在第二条语句中,您的代码在pd undefined时失败,随后,嵌入文本中出现语法错误。功能和功能对问题无关紧要。您忽略了包含完整的输出—我希望printage能够清楚地显示问题所在,正如您的第一位评论员所指出的那样。@Alexander:您的代码还远没有达到最小值,请尝试将其减少到几行,以说明错误的一次发生。我们不需要函数定义行def process_datadf:。我们不需要为pf-in-person\u-filter:打开循环,您可以选择“Jason”作为您的MCVE示例。因此,第一行是:age=df1[df1.first_name=='Jason'][['age']]].astypestr.astypeint。您甚至不需要age中的循环:毕竟,这是不必要的代码,ag是单个值,而不是列表或序列。等等
for ag in age.values: