Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 519
cah Avatar asked Aug 15 '26 16:08

cah


1 Answers

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
like image 162
brandomr Avatar answered Aug 18 '26 04:08

brandomr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!