Dataframe 基于表中的另一列值有条件地填充列值

Dataframe 基于表中的另一列值有条件地填充列值,dataframe,pandas,Dataframe,Pandas,我有一个带有几列的DataFrame。其中一列包含使用货币的符号,例如欧元或美元符号。另一列包含预算值。例如,在一行中,它可能意味着5000欧元的预算,而在下一行中,它可能意味着2000美元的预算 在pandas中,我想在我的数据框架中添加一个额外的列,将预算标准化为欧元。因此,基本上,对于每一行,如果货币列中的符号是欧元符号,则新列中的值应为预算列*1的值,如果货币列中的符号是美元符号,则新列中的值应为预算列*0.78125的值 我知道如何添加列、用值填充列、从另一列复制值等,但不知道如何根据

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

在pandas中,我想在我的数据框架中添加一个额外的列,将预算标准化为欧元。因此,基本上,对于每一行,如果货币列中的符号是欧元符号,则新列中的值应为预算列*1的值,如果货币列中的符号是美元符号,则新列中的值应为预算列*0.78125的值

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


有什么建议吗?

你可能想做什么

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

通过另一种样式,类似的结果可能是编写一个函数,使用
row['fieldname']
语法访问单个值/列,然后对其执行所需的操作

这与此处链接的问题的答案相呼应:


进一步考虑Tom Kimber的建议,可以使用函数字典为函数设置各种条件。这种解决办法扩大了问题的范围

我正在使用一个来自个人应用程序的示例

# write the dictionary

def applyCalculateSpend (df_name, cost_method_col, metric_col, rate_col, total_planned_col):
    calculations = {
            'CPMV'  : df_name[metric_col] / 1000 * df_name[rate_col],
            'Free'  : 0
            }
    df_method = df_name[cost_method_col]
    return calculations.get(df_method, "not in dict")

# call the function inside a lambda

test_df['spend'] = test_df.apply(lambda row: applyCalculateSpend(
row,
cost_method_col='cost method',
metric_col='metric',
rate_col='rate',
total_planned_col='total planned'), axis = 1)

  cost method  metric  rate  total planned  spend
0        CPMV    2000   100           1000  200.0
1        CPMV    4000   100           1000  400.0
4        Free       1     2              3    0.0

numpy
不需要额外导入的选项:

df['Normalized']=df['Budget']。其中(df['Currency']=='$',df['Budget']*0.78125)

可以用文字而不是数字来做这样的事情吗?df['Qnty']=np.where(df['Quantity'].str.extract('([a-z]+)=='g',df['Quantity'].str.extract('(\d+).astype(int)/1000,df['Quantity'].str.extract('(\d+).astype(int))不知道是否有人需要它,但我还是发布了。那应该是
lambda行:normalise_行(row)
?难道你就不能用
normalise\u row
来代替整个事情吗?
# write the dictionary

def applyCalculateSpend (df_name, cost_method_col, metric_col, rate_col, total_planned_col):
    calculations = {
            'CPMV'  : df_name[metric_col] / 1000 * df_name[rate_col],
            'Free'  : 0
            }
    df_method = df_name[cost_method_col]
    return calculations.get(df_method, "not in dict")

# call the function inside a lambda

test_df['spend'] = test_df.apply(lambda row: applyCalculateSpend(
row,
cost_method_col='cost method',
metric_col='metric',
rate_col='rate',
total_planned_col='total planned'), axis = 1)

  cost method  metric  rate  total planned  spend
0        CPMV    2000   100           1000  200.0
1        CPMV    4000   100           1000  400.0
4        Free       1     2              3    0.0