根据pandas中的其他列值有条件地填充列值

Jan*_*ulp 31 dataframe pandas

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

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

我知道如何添加一列,其值填充它,从另一列等的值复制但不知道如何有条件地基于其他列的值填充新列.

有什么建议?

Wes*_*ney 61

你可能想做

df['Normalized'] = np.where(df['Currency'] == '$', df['Budget'] * 0.78125, df['Budget'])
Run Code Online (Sandbox Code Playgroud)

  • 有可能做这样的事情但用文字而不是数字吗? (7认同)
  • df['Qnty'] = np.where(df['数量'].str.extract('([az]+)') == 'g', df['数量'].str.extract('( \d+)').astype(int) / 1000, df['Quantity'].str.extract('(\d+)').astype(int)) 不知道是否有人需要这个,但仍然我已经发布。 (3认同)

Tho*_*ber 7

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

这与此处链接的问题的答案相呼应:pandas基于其他列的值创建新列

def normalise_row(row):
    if row['Currency'] == '$'
    ...
    ...
    ...
    return result

df['Normalized'] = df.apply(lambda row : normalise_row(row), axis=1) 
Run Code Online (Sandbox Code Playgroud)

  • 那应该是`lambda row:normalise_row(row)`吗?难道你不能用`normalise_row`替换整个东西吗? (3认同)

dsh*_*ort 6

不需要额外导入的选项numpy

df['Normalized'] = df['Budget'].where(df['Currency']=='$', df['Budget'] * 0.78125)
Run Code Online (Sandbox Code Playgroud)


Art*_*nko 5

将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
Run Code Online (Sandbox Code Playgroud)