Reputation: 3064
How can I get a column value from a row given that this row was found using another value form another column? For example:
row = df.loc[df['Name'] == 'john']
and now I would like to get his email with something like this row['email']
Upvotes: 2
Views: 267
Reputation: 164843
You have a few options. Note the below includes no error-handling. It's assumed the given name exists.
pd.DataFrame.loc
+ pd.Series.values
This accesses the underlying NumPy array and extracts the first item:
df.loc[df['Name'] == 'john', 'email'].values[0]
pd.DataFrame.at
Set your index to Name
, then use at
. Assumes your names are unique, otherwise scalar access in this way may not make sense.
df.set_index('Name').at['john', 'email']
If you do this often, I recommend you store df.set_index('Name')
to avoid expensive repeat operations.
pd.Series.loc
Similar to the first solution but utilising pd.Series
methods:
df['email'].loc[df['Name'].eq('john').index[0]]
Upvotes: 1
Reputation: 4792
You could use df.get_value
too if you have
syntax:
DataFrame.get_value(index, col, takeable=False)
Example
df.get_value(1, 'email')
Here one is the index of the row
or df.at[]
df.at[1, 'email']
Upvotes: 0
Reputation: 1753
df.loc
is a row and column indexer. So you can simply do
df.loc[df['Name'] == 'john', 'email']
Upvotes: 0