user1179317
user1179317

Reputation: 2903

extracting a single data from pandas data frame

How do you extract a value (string) from a given Dataframe, given a certain value from a different column.

For example, I would like to get the 'Adrs' where 'Value'=2

import pandas as pd

df = pd.DataFrame({'Adrs':["AAA","BBB"],'Value':[1,2]}, index=[0,1])

print(df)
print("")

df2 = df[df['Value']==2]
string = df2.Adrs
print(string)

Output:

Adrs  Value
0  AAA      1
1  BBB      2

1    BBB
Name: Adrs, dtype: object

I would like to extract just the "BBB" instead of that entire table/data frame. Is there a quick way to do this without doing some parsing of the df2.Adrs

If df2 has multiple rows, I can extract BBB by df2['Adrs'][1]

see below:

import pandas as pd

df = pd.DataFrame({'Adrs':["AAA","BBB"],'Value':[2,2]}, index=[0,1])

print(df)
print("")

df2 = df[df['Value']==2]
string = str(df2['Adrs'][1])
print(string)

output:

 Adrs  Value
0  AAA      2
1  BBB      2

BBB

Upvotes: 0

Views: 7331

Answers (2)

Jarad
Jarad

Reputation: 18883

>>> df.loc[df['Value'] == 2, 'Adrs'].values[0]
'BBB'
>>> df.iat[1, 0]
'BBB'
>>> df.at[1, 'Adrs']
'BBB'

Are a few ways. I'm sure there's more.

Upvotes: 2

Rgaddi
Rgaddi

Reputation: 455

df2.Adrs is still a Series, so what you want to do is grab one element from it. df2.Adrs.iloc(0) will get you the first element, regardless of indexing. But what will you do if df2 has multiple rows?

Upvotes: 0

Related Questions