Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas: Create new column based on mapped values from another column [duplicate]

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.

like image 257
Alexandros Giannakakis Avatar asked Sep 12 '25 09:09

Alexandros Giannakakis


1 Answers

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.

like image 118
S3DEV Avatar answered Sep 14 '25 23:09

S3DEV