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

标签 python pandas dataframe

我有一个数据框,其中包含度量列 SalesMonth1 -- SalesMonth12 以及另一列 Indexprice

我正在尝试执行以下操作,但它不起作用。您能提出更好的方法吗?

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

最佳答案

你很接近。试试这个:

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

诀窍是通过 str 将整数转换为字符串。

关于python - 迭代 Pandas 数据框中的多个列并创建新列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49411605/

相关文章:

python - 修剪字符串列表中的单词

python - 如何将qint32的结果转换为quint8

python - 在 pandas 中使用 groupby 进行 bool 运算

Python数据框排名系列

python - 使用 Python 中的 Pandas,仅选择 group by group count 为 1 的行

python - 如何有效地检查 Spark Dataframe 中是否包含单词列表?

Python组合目录中的所有csv文件并按日期时间排序

python - 你能用 Python 在 MS Windows 上将标准输入作为文件打开吗?

python - 识别重复值并向其附加唯一字符串

python - 查询 pandas DataFrame 时出现 UndefinedVariableError