English 中文(简体)
有条件填充基于熊猫中其他列值的列值
原标题:Conditionally fill column values based on another columns value in pandas

我有一个 < code> DataFrame < /code >, 上面有几栏。 一列包含一个货币使用的符号, 例如欧元或美元符号。 另一列包含一个预算值。 例如, 一行它可能意味着以欧元计的预算为5000欧元,下一行它可以说以美元计的预算为2000美元。

在熊猫中,我想在我的 DataFrame 中增加一列,使预算以欧元正常化。 因此,对于每一行,新列的值应该是预算列的值 * 1,如果货币栏中的符号是欧元符号,新列的值应该是预算列的值 * 0.78125,如果货币栏中的符号是美元符号。

我知道如何添加一列, 填满其他列的值、 复制值等等, 而不是根据另一列的值 有条件地填充新列 。

有什么建议吗?

最佳回答

你也许想做

df[ Normalized ] = np.where(df[ Currency ] ==  $ , df[ Budget ] * 0.78125, df[ Budget ])
问题回答

通过其它样式的类似结果可能是写入一个函数,该函数使用 row[ fieldname] syntatus 来访问单个值/ colunns,然后执行 < a href=> http://pandas.pydata.org/pandas-docs/stable/pendas/pandas.DataFrame.aply.html" rel=“noreferr>>dataFrame. apply 方法进行您想要的操作。

这回应了在此关联的问题的答案 : < a href=""https://stackoverflow.com/ questions/26886653/pandas-create-new-colun- based- values- from- other- columns/ 26887820#26887820" >pandas根据其他栏目 的数值创建新栏目

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

df[ Normalized ] = df.apply(lambda row : normalise_row(row), axis=1) 

无需额外导入 numpy 的选项 :

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

用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

Panda s 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
df.loc[df[ col1 ].isnull(),  col2 ] = values




相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签