简体   繁体   中英

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
>>> 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.

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM