4

I want to create a new column based on conditions from another one in Python. More specifically, one of my columns in the dataframe is:

Kilos:
1. 8.0
2. 16.0
3. 12.0
4. 10.0
5. 5.0
...

I want the new column to be based on this column and every time you find a row (in the kilos column) where the kilos are 8.0, then the new's column row will write 'X2 + parts' and when the column is 16.0 the row of the new column will write 'X8 + parts', for the other columns I don't care. They can be blank or anything else.

S3DEV
  • 8,768
  • 3
  • 31
  • 42

2 Answers2

5

In the example below, you will create a value map dictionary (valmap) which will be used to map your 8.0 and 16.0 values to the text you require.

Sample Code:

import pandas as pd

# Create dataset.
data = {'Kilos': [8.0, 16.0, 12.0, 10.0, 5.0]}
df = pd.DataFrame(data)

# Create a value map dict for mapping specific values.
valmap = {8.0: 'X2 + parts', 16.0: 'X8 + parts'}
# Apply the value map into a new column.
df['Text'] = df['Kilos'].map(valmap)

# Show the results.
print(df)

Output:

   Kilos        Text
0    8.0  X2 + parts
1   16.0  X8 + parts
2   12.0         NaN
3   10.0         NaN
4    5.0         NaN

Hope this helps point you in the right direction.

S3DEV
  • 8,768
  • 3
  • 31
  • 42
0

You could use np.select(). You create your conditions and you populate them into the method, along with the result you want for each condition.

Below is your initial dataframe, then the conditions and the use of np.select():

df=pd.DataFrame({'kilos':[8.0, 16.0, 12.0, 10.0, 5.0]})
df
   kilos
0    8.0
1   16.0
2   12.0
3   10.0
4    5.0

kilos_8 = df['kilos']==8   #condition 1
kilos_16 = df['kilos']==16  #condition 2

df['new_col']=np.select([kilos_8, kilos_16],
                        ['X2 + parts', 'X8 + parts'],
                          default=np.nan)
df
   kilos     new_col
0    8.0  X2 + parts
1   16.0  X8 + parts
2   12.0         nan
3   10.0         nan
4    5.0         nan
Newbielp
  • 431
  • 3
  • 16