cah
cah

Reputation: 31

Python Pandas create new column in loop

I'm attempting to create a new column for each column by dividing two columns. df is a pandas dataframe...

columns = list(df.columns.values)
for column_1 in columns: 
    for column_2 in columns:         
        new_column = '-'.join([column_1,column_2])
        df[new_column] = df[column_1] / df[column_2]

Getting an error: NotImplementedError: operator '/' not implemented for bool dtypes

Any thoughts would be appreciate?

Upvotes: 3

Views: 7248

Answers (1)

brandomr
brandomr

Reputation: 302

Like Brian said you're definitely trying to divide non-numeric columns. Here's a working example of dividing two columns to create a third:

name = ['bob','sam','joe']
age = [25,32,50]
wage = [50000, 75000, 32000]

people = {}
for i in range(0,3):
    people[i] = {'name':name[i], 'age':age[i],'wage':wage[i]}

# you should now have a data frame where each row is a person
# you have one string column (name), and two numerics (age and wage)        
df = pd.DataFrame(people).transpose()

df['wage_per_year'] = df['wage']/df['age']

print df

Upvotes: 3

Related Questions