Chubaka
Chubaka

Reputation: 3135

python3 pandas move data into new columns if condition met

If I have a dataframe:

names,individual
ABC LLC, business
John Smith, individual

How can I shift the names into a new column called 'businessname' if the 'individual' column='business'?

Desired output:

names,individual,businessname
null, business, ABC LLC
John Smith, individual, null

Thanks!

Upvotes: 0

Views: 63

Answers (2)

Ale
Ale

Reputation: 1345

There are probably several ways to move data into a column. One way particular to your problem is creating a column with selected data.

The following code creates a dataframe with your data

import pandas as pd

# Contruct dataframe
# names,individual
# ABC LLC, business
# John Smith, individual

df = pd.DataFrame(columns=['names', 'individual'], data=[('ABC LLC', 'business'), ('John Smith', 'individual')])

create a mask to select only business

mask = df['individual'] == 'business'

add new column

df['business name'] = None

get the names from the business and set the business names

df.loc[mask, 'business name'] = df.loc[mask, 'names']

set the column rows of the column 'names' of the businesses to None

df.loc[mask, 'names'] = None

Upvotes: 1

Vaishali2020
Vaishali2020

Reputation: 39

df['businessman']=np.where(df['individual']=='business',df['names'],pd.NaN)
df['names']=np.where(df['individual']=='individual',df['names'],pd.NaN)

Upvotes: 1

Related Questions