我正在处理一个由几个不同的变量组成的数据集。对于这些变量中的每一个,数据集还包括一个“编码”变量。也就是说,这是一种分类变量,它包含有关所指涉的变量的附加信息,如果有关该变量的其他信息,则会提供。
例如:
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
==
等于运算符可能比我的!=
运算符更准确。 - JvdV.groupby
方法中使用多列by
参数让我想到了另一种可能的解决方案,现在我已经进行了编辑。 - Phillyclause89