【问题标题】:DataFrame apply filtering by other columnDataFrame 按其他列应用过滤
【发布时间】:2020-06-05 10:02:02
【问题描述】:

我可以通过过滤具有另一个列值的行来将函数应用于数据框列吗?

我的实际代码是:

df['description_text_clean'] = df.description_text_clean[df['language']!='en'].apply(translate_to_en)

我试图通过非英语的语言来过滤语言列,并且我想翻译 description_text_clean 列。但最后我发现 description_text_clean 列已被 NaN 在英文列中修改,我希望它们继续保持原样。

示例数据框:

df = pd.DataFrame([['Example text', 'en'], 
                   ['No es ingles', 'es'], 
                   ['I am again english', 'en']], 
                   columns=['description_text_clean', 'language'])

实际结果:

    description_text_clean  language
0   NaN                       en
1   It is not English         es
2   NaN                       en

期望的结果是使用 translate_to_en 函数获得一个将所有文本翻译成英文的数据框,该函数使用 google translate api:

    description_text_clean  language
0   Example text              en
1   It is not English         es
2   I am again english        en

有什么建议吗?

【问题讨论】:

  • 感谢您的 cmets @anky。使用此代码,您将在应用要翻译的唯一行中进行提取,但是每当您要将它们插入数据框时,它都会为所有不存在的行(英文行)添加 NaN 值。
  • 我的错,没有意识到 fillna 不会做任何事情,因为我们没有这些索引,这次添加了答案

标签: python pandas dataframe apply


【解决方案1】:

我的错误是我错过了我的 cmets 中的一个小细节,尝试使用 .loc[],series.maskseries.combine_firstnp.where

df.loc[df['language'].ne('en'),'description_text_clean']  = (
                     df['description_text_clean'].map(fun))

或者:

(df.loc[df['language'].ne('en'),'description_text_clean'].map(translate_to_en)
  .combine_first(df.description_text_clean))

或者:

df['description_text_clean'].mask(df['language'].ne('en')
                                  ,df['description_text_clean'].map(translate_to_en))

甚至np.where:

np.where(df['language'].ne('en'),
        df['description_text_clean'].map(fun),df['description_text_clean'])

用虚拟函数测试:

def fun(x):
    return  1
df['description_text_clean'] =(df.loc[df['language'].ne('en'),'description_text_clean']
                      .map(fun).combine_first(df.description_text_clean))

或者:

df['description_text_clean'] = df['description_text_clean'].mask(df['language'].ne('en')
                              ,df['description_text_clean'].map(fun))
print(df)

  description_text_clean language
0           Example text       en
1                      1       es
2     I am again english       en

【讨论】:

  • 感谢@anky,它适用于您的解决方案!有什么方法可以申请吗?
  • @IMB 只需将我的解决方案中的 map 替换为 apply 但 IMO 地图应该表现更好
  • 我已经尝试了所有这些,我将使用 np.where 因为它是最快的。排名如下(使用玩具数据框): 1.- Numpy
猜你喜欢
  • 2019-06-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-13
  • 1970-01-01
  • 2021-09-10
相关资源
最近更新 更多