Lilian417
Lilian417

Reputation: 59

Get a value of a column by using another column's value

          user     min     max
1         Tom        1       5
2         Sam        4       6

I got this dataframe, now I know the user is Sam and I wanna get its 'min' value. Like this (the user is unique):

df[Sam,'min'] = 4

How can I do this?

Upvotes: 1

Views: 41

Answers (2)

jezrael
jezrael

Reputation: 862641

First create index by column userid by set_index and then select by loc:

df = df.set_index('user')
print (df.index)
Index(['Tom', 'Sam'], dtype='object', name='user')

a = df.loc['Sam','min']
print (a)
4

Or use boolean indexing with loc, but because get Series is necessary select again:

a = df.loc[df['user'] == 'Sam','min'].values[0]

Upvotes: 2

jpp
jpp

Reputation: 164673

Using set_index + pd.DataFrame.at for accessing a scalar:

res = df.set_index('user').at['Sam', 'min']

print(res)
4

Upvotes: 1

Related Questions