Augusto Baldo
Augusto Baldo

Reputation: 119

How to pick some values of a column and make another one with them?

This is a table similar to the one I'm working with

      A     B   
0   12.2   43
1   10.1   32
2    3.4   34
3   12.0   55
4   40.6   31

And what I'm trying to do is take some values of the column A that follow a certain pattern and create another column with such values. For example, the column C would have only the values from A that are bigger than 12, and column D the ones smaller or equal:

      A     B      C     D 
0   12.2   43    12.2   NaN 
1   10.1   32     NaN   10.1
2    3.4   34     NaN   3.4 
3   12.0   55     NaN   12.0
4   40.6   31    40.6   NaN

I've tried making a list for each group of values, but I can't merge them back with the original table, since there are some numbers that repeat and the number of columns grow. I think there's an esasier way to do that, but I can't seem to find it. How can I do that?

Upvotes: 1

Views: 52

Answers (3)

Andrej Kesely
Andrej Kesely

Reputation: 195553

And another version:

df['C'] = df.loc[df.A > 12, 'A']
df['D'] = df.loc[df.A <= 12, 'A']

print(df)

Prints:

      A   B     C     D
0  12.2  43  12.2   NaN
1  10.1  32   NaN  10.1
2   3.4  34   NaN   3.4
3  12.0  55   NaN  12.0
4  40.6  31  40.6   NaN

Upvotes: 3

BENY
BENY

Reputation: 323366

Let us try np.where

df['C']=np.where(df.A>12,df.A,np.nan)
df['D']=np.where(df.A<=12,df.A,np.nan)
df
      A   B     C     D
0  12.2  43  12.2   NaN
1  10.1  32   NaN  10.1
2   3.4  34   NaN   3.4
3  12.0  55   NaN  12.0
4  40.6  31  40.6   NaN

Upvotes: 1

Quang Hoang
Quang Hoang

Reputation: 150785

Isn't it mask and where:

mask = df['A']>12
df['C'] = df['A'].where(mask)
df['D'] = df['A'].mask(mask)

Output:

      A   B     C     D
0  12.2  43  12.2   NaN
1  10.1  32   NaN  10.1
2   3.4  34   NaN   3.4
3  12.0  55   NaN  12.0
4  40.6  31  40.6   NaN

Upvotes: 1

Related Questions