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.
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.
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With