确定字符串在熊猫DataFrame中包含什么语言

时间:2020-01-06 10:04:10

标签: python pandas textblob

我是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 Dataframe。

我已经尝试过:

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中每行的语言?

谢谢您的建议。

1 个答案:

答案 0 :(得分:3)

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