首页 > 解决方案 > 确定一个字符串在 pandas DataFrame 中包含什么语言

问题描述

我是 Pandas 和 Python 的新手。

我的数据框:

df

Text
Best tv in 2020
utilizar un servicio sms gratuito
utiliser un tv pour netflix

我想要的输出

Text                                    Language
Best tv in 2020                         en
utilizar un servicio sms gratuito       es
utiliser un tv pour netflix             fr

我正在使用什么:

from textblob import TextBlob

b = TextBlob("utilizar un servicio sms gratuito")
print(b.detect_language())

>>es

我不确定如何集成此方法来填充我的 Pandas 数据框。

我努力了:

df['Language'] = TextBlob(df['Text']).detect_language()

但我收到一个错误:

TypeError: The `text` argument passed to `__init__(text)` must be a string, not <class 'pandas.core.series.Series'>

我明白这意味着什么,我需要传递一个字符串而不是 pandas DataFrame 系列,所以我的问题是如何循环整个系列以检测列中每行的语言text

谢谢你的建议。

标签: pythonpandastextblob

解决方案


Series.apply与 lambda 函数一起使用:

df['Language'] = df['Text'].apply(lambda x: TextBlob(x).detect_language())

或者Series.map

df['Language'] = df['Text'].map(lambda x: TextBlob(x).detect_language())

print (df)
                                Text Language
0                    Best tv in 2020       en
1  utilizar un servicio sms gratuito       es
2        utiliser un tv pour netflix       fr

推荐阅读