根据另一列pandas dataframe提取列值

时间:2022-04-19 09:34:04

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.

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

3 个解决方案

#1


52  

You could use loc to get series which satisfying your condition and then iloc to 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'

#2


10  

You can try query, which is less typing:

您可以尝试查询,这样可以减少输入:

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

#3


7  

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

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

#1


52  

You could use loc to get series which satisfying your condition and then iloc to 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'

#2


10  

You can try query, which is less typing:

您可以尝试查询,这样可以减少输入:

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

#3


7  

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

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