简体   繁体   English

迭代 Pandas 数据框中的多列并创建新列

[英]Iterate over multiple columns in Pandas dataframe and create new columns

I have a dataframe with measure columns SalesMonth1 -- SalesMonth12 and another columns Index and price .我有一个带有度量列SalesMonth1 - SalesMonth12和另一列Indexprice的数据SalesMonth1

I am trying to do the following but it does not work.我正在尝试执行以下操作,但它不起作用。 Could you please suggest a better way?你能提出更好的方法吗?

For i in range(12):
     DF['Newcol'] = np.where(DF["Index"] >0,
                             DF["SalesMonth[i]"] * DF["price"],
                             DF["SalesMonth[i]"])

You are close.你很近。 Try this:尝试这个:

for i in range(12):
    df['newcol'+str(i)] = np.where(df['Index'] > 0,
                                   df['SalesMonth'+str(i)] * df['price'],
                                   df['SalesMonth'+str(i)])

The trick is to convert your integers to strings via str .诀窍是通过str将整数转换为字符串。

Use loc for in-place assignment (very cheap, fast).使用loc进行就地分配(非常便宜,快速)。

m = df["Index"] > 0
df.loc[m, 'SalesMonth1':'SalesMonth12'] *= df.loc[m, 'Price']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM