我试图创建一个函数,该函数针对给定的条件为给定的ID转换标签列。
我想根据该ID的 * 最常用标签 * 来标准化标签,如果没有common/majority标签,那么就将第一个观察结果作为默认标准。
到目前为止,我的功能如下:
def standardize_labels(df, id_col, label_col):
# Function to find the most common label or the first one if there's a tie
def most_common_label(group):
labels = group[label_col].value_counts()
# Check if the top two labels have the same count
if len(labels) > 1 and labels.iloc[0] == labels.iloc[1]:
return group[label_col].iloc[0]
return labels.idxmax()
# Group by the ID column and apply the most_common_label function
common_labels = df.groupby(id_col).apply(most_common_label)
# Map the IDs in the original DataFrame to their common labels
df['standardized_label'] = df[id_col].map(common_labels)
return df
字符串
它 * 大部分 * 工作,但是我注意到一些奇怪的地方,标签中的趋势发生了变化,然后每个给定的ID的标签都会发生变化,如下所示:
| ID|原始标号|标准化标号|
| --|--|--|
| 222 |洛杉矶地铁|洛杉矶地铁|
| 222 |洛杉矶地铁|洛杉矶地铁|
| 222 |洛杉矶地铁|洛杉矶地铁|
| 222 |洛杉矶地铁|洛杉矶地铁|
| 222 |洛杉矶地铁|洛杉矶地铁|
相反,当输出时,我希望所有的standardized_label都是LA Metro,因为这是每个ID的多数标签。
1条答案
按热度按时间vwkv1x7d1#
这段代码对我来说和预期的一样。但是,你可以使用
mode
来使它更容易阅读。你也可以将groupby中的函数转换为直接赋值给列,这样你的整个操作就变成了一行代码。字符串
或者你也可以使用
groupby.apply
并Map它。无论如何,函数看起来像这样:型
由于
value_counts()
工作在一个框架上,我们可以直接使用它而不需要groupby。所以函数可以改为下面的。这是我为另一个问题写的a function的重构。型