user7779326
user7779326

Reputation:

How to obtain the matching ID separately as a new column?

I have the following data.

df['íd'] = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O']
df['value'] = ['12','12','13','12','13','12','13','12','12','15','17','12','13','12','15']

how to obtain the id separately as a new column if its corresponding value is equal to 12 ?

Upvotes: 1

Views: 70

Answers (2)

John
John

Reputation: 1272

Here are few simplest ways to do it.

df['new'] = df[df.value == '12']['id']
OR
df['new'] = df.query('value == "12"')['id']
OR
df['new'] = df['id'].where(df['value'] == '12')

Upvotes: 0

jezrael
jezrael

Reputation: 862751

I think you need loc or where:

df = pd.DataFrame()
df['id'] = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O']
df['value'] = ['12','12','13','12','13','12','13','12','12','15','17','12','13','12','15']

df.loc[df['value'] == '12', 'new'] = df['id']
print (df)
   id value  new
0   A    12    A
1   B    12    B
2   C    13  NaN
3   D    12    D
4   E    13  NaN
5   F    12    F
6   G    13  NaN
7   H    12    H
8   I    12    I
9   J    15  NaN
10  K    17  NaN
11  L    12    L
12  M    13  NaN
13  N    12    N
14  O    15  NaN

df['new'] = df['id'].where(df['value'] == '12')
print (df)
   id value  new
0   A    12    A
1   B    12    B
2   C    13  NaN
3   D    12    D
4   E    13  NaN
5   F    12    F
6   G    13  NaN
7   H    12    H
8   I    12    I
9   J    15  NaN
10  K    17  NaN
11  L    12    L
12  M    13  NaN
13  N    12    N
14  O    15  NaN

EDIT:

For comparing with numbers remove '':

df = pd.DataFrame()
df['id'] = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O']
df['value'] = [12,12,13,12,13,12,13,12,12,15,17,12,13,12,15]

df.loc[df['value'] == 12, 'new'] = df['id']
print (df)
   id  value  new
0   A     12    A
1   B     12    B
2   C     13  NaN
3   D     12    D
4   E     13  NaN
5   F     12    F
6   G     13  NaN
7   H     12    H
8   I     12    I
9   J     15  NaN
10  K     17  NaN
11  L     12    L
12  M     13  NaN
13  N     12    N
14  O     15  NaN

Upvotes: 1

Related Questions