python - 确定一个字符串在 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
?
谢谢你的建议。
解决方案
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
推荐阅读
- php - 如何在php中使用exec运行多个命令
- google-cloud-platform - Google Cloud Functions 实现互斥锁的模式是什么
- c# - 自托管 Owin ASP.NET web api 仅接受 localhost 连接
- python - 没有为 Django==2.2 找到匹配的发行版
- c# - 如何实现从子类到父类的返回方法?
- c# - 从标记为多个的选择控件接收所有选定的选项
- android - Android改造演示列表视图不显示所有回购
- matlab - 3D 图中的轴方向
- jquery - 如果我的 AMP 网页不符合 AMP 标准怎么办
- python-3.x - PCA解释方差比的解释