Print the raw value of a column alone, in pandas?

后端 未结 3 400
栀梦
栀梦 2020-11-29 12:20

I have a dataframe:

df = pd.DataFrame([ { \'name\': \'george\', \'age\': 23 }, {\'name\': \'anna\', \'age\': 26}])

Now I want to retrive Ge

相关标签:
3条回答
  • 2020-11-29 12:43

    Might as well make my comment an answer:

    df[df.name == 'george'].age.values[0]
    

    or

    int(df[df.name == 'george'].age)
    

    should work

    0 讨论(0)
  • 2020-11-29 12:47

    You can use loc + values for converting Serie to numpy array and then select first value by [0]:

    print (df.loc[df.name == 'george', 'age'].values)
    [23]
    print (df.loc[df.name == 'george', 'age'].values[0])
    23
    

    Or simply select first value of Series with iloc:

    print (df.loc[df.name == 'george', 'age'].iloc[0])
    23
    

    Or select first item by iat:

    print (df.loc[df.name == 'george', 'age'].iat[0])
    23
    

    Or use Series.item:

    print (df.loc[df.name == 'george', 'age'].item())
    23
    

    If possible no match value, above solutions failed.

    Then is possible use next with iter trick:

    print (next(iter(df.loc[df.name == 'george', 'age']),'no match value'))
    23
    
    print (next(iter(df.loc[df.name == 'jano z hornej dolnej', 'age']),'no match value'))
    no match value
    
    0 讨论(0)
  • 2020-11-29 12:52
    df = [ { 'name': 'george', 'age': 23 }, {'name': 'anna', 'age': 26}]
    k = [x['age'] for x in df if x['name'] == 'george']
    print k 
    
    0 讨论(0)
提交回复
热议问题