Python 基于另一列熊猫数据框提取列值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36684013/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 18:13:38  来源:igfitidea点击:

extract column value based on another column pandas dataframe

pythonpandasdataframe

提问by Anderson Zhu

I am kind of getting stuck on extracting value of one variable conditioning on another variable. For example, the following dataframe:

我有点卡在提取一个变量条件下另一个变量的值上。例如,以下数据框:

A  B
p1 1
p1 2
p3 3
p2 4

How can I get the value of Awhen B=3? Every time when I extracted the value of A, I got an object, not a string.

我怎样才能获得Awhen的价值B=3?每次提取 的值时A,都会得到一个对象,而不是字符串。

回答by Anton Protopopov

You could use locto get series which satisfying your condition and then ilocto get first element:

您可以使用loc获取满足您条件的系列,然后iloc获取第一个元素:

In [2]: df
Out[2]:
    A  B
0  p1  1
1  p1  2
2  p3  3
3  p2  4

In [3]: df.loc[df['B'] == 3, 'A']
Out[3]:
2    p3
Name: A, dtype: object

In [4]: df.loc[df['B'] == 3, 'A'].iloc[0]
Out[4]: 'p3'

回答by PhilChang

You can try query, which is less typing:

你可以试试query,这是少打字:

df.query('B==3')['A']

回答by emited

df[df['B']==3]['A'], assuming df is your pandas.DataFrame.

df[df['B']==3]['A'],假设 df 是你的 pandas.DataFrame。

回答by Baz

Use df[df['B']==3]['A'].valuesif you just want item itself without the brackets

df[df['B']==3]['A'].values如果您只想要没有括号的项目本身,请使用

回答by Dheeraj Pranav

male_avgtip=(tips_data.loc[tips_data['sex'] == 'Male', 'tip']).mean()

I have also worked on this clausing and extraction operations for my assignment.

我还为我的作业研究了这个从句和提取操作。