Python Pandas 在循环中创建新列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32534005/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 23:52:42  来源:igfitidea点击:

Python Pandas create new column in loop

pythonloopspandas

提问by cah

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

我试图通过划分两列为每列创建一个新列。df 是一个Pandas数据框...

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

收到错误:NotImplementedError:没有为 bool dtypes 实现运算符“/”

Any thoughts would be appreciate?

任何想法将不胜感激?

回答by brandomr

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