numpy 根据pandas中的另一个列值连续填充列值

tct7dpnv  于 12个月前  发布在  其他
关注(0)|答案(6)|浏览(81)

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

of1yzvn4

of1yzvn41#

你可能想做

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

bbuxkriu2#

通过另一种方式,类似的结果可能是编写一个函数,对一行执行所需的操作,使用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)
r7knjye2

r7knjye23#

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

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

7ajki6be4#

把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
eoxn13cs

eoxn13cs5#

Panda的loc也可以用于:

# First assign Budget to the entire column
df['Normalized'] = df['Budget']
# Then convert to dollars where necessary
df.loc[df['Currency'] == '$', 'Normalized'] = df['Budget'] * 0.78125
b4lqfgs4

b4lqfgs46#

df.loc[df['col1'].isnull(), 'col2'] = values

相关问题