简体   繁体   English

从熊猫数据框中提取单个数据

[英]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. 如何从给定的Dataframe中提取值(字符串),并从不同的列中获取给定的值。

For example, I would like to get the 'Adrs' where 'Value'=2 例如,我想获得“价值” = 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. 我只想提取“ BBB”而不是整个表/数据框。 Is there a quick way to do this without doing some parsing of the df2.Adrs 是否有一种快速的方法可以执行此操作而无需对df2进行一些解析。

If df2 has multiple rows, I can extract BBB by df2['Adrs'][1] 如果df2有多行,我可以通过df2 ['Adrs'] [1]提取BBB

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仍然是一个Series,因此您想要从中获取一个元素。 df2.Adrs.iloc(0) will get you the first element, regardless of indexing. df2.Adrs.iloc(0)将使您获得第一个元素,而不管索引如何。 But what will you do if df2 has multiple rows? 但是,如果df2有多行怎么办?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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