在pandas DataFrame中根据另一列的值对数值进行替换

3

我正在处理一个由几个不同的变量组成的数据集。对于这些变量中的每一个,数据集还包括一个“编码”变量。也就是说,这是一种分类变量,它包含有关所指涉的变量的附加信息,如果有关该变量的其他信息,则会提供。

例如:

data = { year: [2000, 2001, 2000, 2001],
         observation: ['A', 'A', 'B', 'B'],
         height: [1, 2, 3, 4],
         height_code: ['S', 'BF', 'BF', 'S'] }

df = pd.DataFrame(data)


在此示例中,如果coding变量取值为'BF',则代表赤脚。也就是说,在测量身高时,这个人没有穿任何鞋子。相反,'S'代表穿鞋。
现在,我需要确定哪些人在穿鞋时测量他们的身高,并且: (1) - 将他们的身高转换为np.nan,以便它们不会在稍后的年度平均身高计算中包含。 或者 (2) - 生成一个新的数据框,其中穿鞋时测量的人从该数据框中删除。然后,我需要按年份计算平均身高,并将其添加到另一个数据框中。
为了使事情清楚:这是一个通用的例子。我的数据集包含许多不同的变量,每个变量可能都有需要考虑的代码,或者可能没有编码(在这种情况下,我不需要关心该观察值的值)。因此,真正的问题是我可能有包含4个变量的观察值(行),其中有2个变量被编码(因此它们的值必须在后续的计算中被忽略),而另外2个变量没有编码(必须考虑它们)。因此,我不能完全舍弃这个观察值,但必须更改2个编码变量中的值,以便在计算中忽略它们。(假设我必须独立地按年份计算每个变量的平均数)
我尝试过的方法: 我编写了这两个函数版本。第二个函数必须传递给DataFrame的.apply()方法。但是,它至少要应用4次(每个目标变量/代码变量对一次,我在这里将编码变量称为test_col)...
# sub_val / sub_value -
# This function goes through each row in a pandas DataFrame and each time/iteration the 
# function will [1] check one of the columns (the "test_col") against a specific value 
# (maybe passed in as an argument, maybe default null value). [2] If the check returns 
# True, then the function will replace the value of another column (the "target_col") 
# in the same row for np.nan . [3] If the check returns False, the fuction will skip to
# the next row.

# - This version is inefficient because it creates one Series object for every
#   row in the DataFrame when iterating through it.
def sub_val(df, target_col, test_col, test_val) :

    # iterate through DataFrame's rows - returns lab (row index) and row (row values as Series obj)
    for lab, row in df.iterrows() : 

        # if observation contains combined data code, ignore variable value
        if row[test_col] == test_val :
            df.loc[lab, target_col] = np.nan # Sub current variable value by NaN (NaN won't count in yearly agg value)

    return df

# - This version is more efficient.
#   Parameters:
#   [1] obs - DataFrame's row (observation) as Series object
#   [2] col - Two strings representing the target and test columns' names
#   [3] test_val - The value to be compared to the value in test_col
def sub_value(obs, target_col, test_col, test_val) :

    # Check value in the column being tested.
    if obs[test_col] == test_val :
        # If condition holds, it means target_col contains a so-called "combined" value
        # and should be ignored in the calculation of the variable by year.
        obs[target_col] = np.nan # Substitute value in target column for NaN
    else :
        # If condition does not hold, we can assign NaN value to the column being tested
        # (i.e. the combined data code column) in order to make sure its value isn't 
        # some undiserable value.
        obs[test_col] = np.nan

    return obs # Returns the modified row
3个回答

1

或者(2)- 生成一个替代的DataFrame,在这个新的DF中删除穿鞋测量的人。然后,我需要按年计算平均身高,并将其添加到另一个DF中。

在这里,切片和pandas.DataFrame.groupby将是您的好朋友:

import pandas as pd

data = dict(
    year = [2000, 2001, 2000, 2001, 2001],
    observation = ['A', 'A', 'B', 'B', 'C'],
    height = [1, 2, 3, 4, 1],
    height_code = ['S', 'BF', 'BF', 'S', 'BF'],
)

df = pd.DataFrame(data)

df_barefoot = df[df['height_code'] == 'BF']
print(df_barefoot)

mean_barefoot_height_by_year = df_barefoot.groupby('year').mean()
print(mean_barefoot_height_by_year)


在Python Tutor中的示例

编辑:您也可以跳过创建第二个df_barefoot的整个过程,只需按'year''height_code'进行groupby

import pandas as pd

df = pd.DataFrame(dict(
    year = [2000, 2001, 2000, 2001, 2001],
    observation = ['A', 'A', 'B', 'B', 'C'],
    height = [1, 2, 3, 4, 1],
    height_code = ['S', 'BF', 'BF', 'S', 'BF'],
))

mean_height_by_year_and_code = df.groupby(['year','height_code']).mean()
print(mean_height_by_year_and_code)


Python Tutor中的示例2


1
好答案。我有点慢,但想到了使用groupby的相同方法。你的==等于运算符可能比我的!=运算符更准确。 - JvdV
谢谢 @JvdV!你在 .groupby 方法中使用多列 by 参数让我想到了另一种可能的解决方案,现在我已经进行了编辑。 - Phillyclause89

0
你想要每个观测类别的平均值吗?那么可能需要这样做:
import pandas as pd
data = {'year': [2000, 2001, 2000, 2001, 2001, 2001],
        'observation': ['A', 'A', 'B', 'B', 'C', 'C'],
        'height': [1, 2, 3, 4, 5, 7],
        'height_code': ['S', 'BF', 'BF', 'S', 'BF', 'BF'] }
df = pd.DataFrame(data)
after = df[df.height_code != 'S'].groupby(['year', 'observation']).mean()

                  height
year observation        
2000 B                 3
2001 A                 2
     C                 6

如果观测值不相关,你想要每年的平均数作为所有观测数据的总和,那么只需使用以下代码:after = df[df.height_code != 'S'].groupby('year').mean()


0

我并没有检查你的实际问题,只是为这个例子写了一个解决方案。

# Separating the data
df = pd.DataFrame(data)
df_bare_foot = df[df["height_code"] == "BF"]
df_shoe = df[df["height_code"] == "S"]

# Calculating Mean separately for 2 different group
mean_df_bf = (
    df_bare_foot
    .groupby(["year"])
    .agg({"height": "mean"})
    .reset_index()
    # that a new way to add a new column when doing other operation
    # equivalant to df["height_code"] = "BF"
    .assign(height_code="BF")
    .rename(columns={"height": "mean_height"})
)

# The mean for shoes category
# we can keep the height_code in group by as
# it is not going to affect the group by
mean_df_sh = (
    df_shoe
    .groupby(["year", "height_code"])
    .agg({"height": "mean"})
    .reset_index()
    .rename(columns={"height": "mean_height"})
)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接