根据 pandas 中的另一个列值有条件地填充列值

2022-01-31 00:00:00 python python-3.x numpy pandas dataframe

问题描述

我有一个包含几列的 DataFrame.一列包含使用货币的符号,例如欧元或美元符号.另一列包含预算值.因此,例如,在一行中,它可能意味着 5000 欧元的预算,而在下一行中,它可能意味着 2000 美元的预算.

I have a DataFrame with a few columns. One columns contains a symbol for which currency is being used, for instance a euro or a dollar sign. Another column contains a budget value. So for instance in one row it could mean a budget of 5000 in euro and in the next row it could say a budget of 2000 in dollar.

在 pandas 中,我想在我的 DataFrame 中添加一个额外的列,以欧元规范化预算.所以基本上,对于每一行,新列中的值应该是预算列中的值 * 1 如果货币列中的符号是欧元符号,新列中的值应该是预算列的值 *如果货币列中的符号是美元符号,则为 0.78125.

In pandas I would like to add an extra column to my DataFrame, normalizing the budgets in euro. So basically, for each row the value in the new column should be the value from the budget column * 1 if the symbol in the currency column is a euro sign, and the value in the new column should be the value of the budget column * 0.78125 if the symbol in the currency column is a dollar sign.

我知道如何添加一列、用值填充它、从另一列复制值等,但不知道如何根据另一列的值有条件地填充新列.

I know how to add a column, fill it with values, copy values from another column etc. but not how to fill the new column conditionally based on the value of another column.

有什么建议吗?


解决方案

你可能想做

df['Normalized'] = np.where(df['Currency'] == '$', df['Budget'] * 0.78125, df['Budget'])

相关文章