根据另一个列熊猫数据框提取列值

问题:根据另一个列熊猫数据框提取列值

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

A  B
p1 1
p1 2
p3 3
p2 4

我如何获得Awhen 的价值B=3?每当我提取的值时A,我都会得到一个对象,而不是字符串。

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 A when B=3? Every time when I extracted the value of A, I got an object, not a string.


回答 0

您可以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'

You could use loc to get series which satisfying your condition and then iloc to get first element:

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'

回答 1

您可以尝试query,输入更少:

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

You can try query, which is less typing:

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

回答 2

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

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


回答 3

使用df[df['B']==3]['A'].values如果你只是想项目本身没有括号

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


回答 4

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

我还为我的任务进行了这种clause和提取操作。

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

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