遍历熊猫dataframe中的多个列并创建新的列

时间:2021-01-01 21:40:11

I have a dataframe with measure columns SalesMonth1 -- SalesMonth12 and another columns Index and price.

我有一个dataframe,有度量列SalesMonth1——SalesMonth12和另一个列索引和价格。

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]"])

2 个解决方案

#1


1  

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将整数转换为字符串。

#2


1  

Use loc for in-place assignment (very cheap, fast).

使用loc进行就地分配(非常便宜、快速)。

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

#1


1  

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将整数转换为字符串。

#2


1  

Use loc for in-place assignment (very cheap, fast).

使用loc进行就地分配(非常便宜、快速)。

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