How to create a new columns conditional on two other columns in python?

Viewed 56

I want to create a new columns conditional on two other columns in python.

Below is the dataframe:

name address
apple hello1234
banana happy111
apple str3333
pie diary5144

I want to create a new column "want", conditional on column "name" and "column" address. The rules are as follows: (1)If the value in "name" is apple, the the value in "want" should be the first five letters in column "address". (2)If the value in "name" is banana, the the value in "want" should be the first four letters in column "address". (3)If the value in "name" is pie, the the value in "want" should be the first three letters in column "address".

The dataframe I want look like this:

name address want
apple hello1234 hello
banana happy111 happ
apple str3333 str33
pie diary5144 dia

How to address such problem? Thanks!

3 Answers

I hope you are well,

import pandas as pd

# Initialize data of lists.
data = {'Name': ['Apple', 'Banana', 'Apple', 'Pie'],
        'Address': ['hello1234', 'happy111', 'str3333', 'diary5144']}

# Create DataFrame
df = pd.DataFrame(data)

# Add an empty column
df['Want'] = ''

for i in range(len(df)):
    if df['Name'].iloc[i] == "Apple":
        df['Want'].iloc[i] = df['Address'].iloc[i][:5]
    if df['Name'].iloc[i] == "Banana":
        df['Want'].iloc[i] = df['Address'].iloc[i][:4]
    if df['Name'].iloc[i] == "Pie":
        df['Want'].iloc[i] = df['Address'].iloc[i][:3]

# Print the Dataframe
print(df)

enter image description here

I hope it helps,

Have a lovely day

I think a broader way of doing this is by creating a conditional map dict and applying it with lambda functions on your dataset.

Creating the dataset:

import pandas as pd

data = {
  'name': ['apple', 'banana', 'apple', 'pie'],
  'address': ['hello1234', 'happy111', 'str3333', 'diary5144']
}

df = pd.DataFrame(data)

Defining the conditional dict:

conditionalMap = {
    'apple': lambda s: s[:5],
    'banana': lambda s: s[:4],
    'pie': lambda s: s[:3]
}

Applying the map:

df.loc[:, 'want'] = df.apply(lambda row: conditionalMap[row['name']](row['address']), axis=1)

With the resulting df:

name address want
0 apple hello1234 hello
1 banana happy111 happ
2 apple str3333 str33
3 pie diary5144 dia

You could do the following:

for string, length in {"apple": 5, "banana": 4, "pie": 3}.items():
    mask = df["name"].eq(string)
    df.loc[mask, "want"] = df.loc[mask, "address"].str[:length]
  • Iterate over the 3 conditions: string is the string on which the length requirement depends, and the length requirement is stored in length.
  • Build a mask via df["name"].eq(string) which selects the rows with value string in column name.
  • Then set column want at those rows to the adequately clipped column address values.

Result for the sample dataframe:

     name    address   want
0   apple  hello1234  hello
1  banana   happy111   happ
2   apple    str3333  str33
3     pie  diary5144    dia
Related