数据框过滤掉非英语文本的行

2024-10-01 02:23:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个pandasdf,它有6列,最后一列是input_text。我想从df中删除该列中包含非英语文本的所有行。我想使用langdetectdetect函数

一些模板

from langdetect import detect
import pandas as pd

def filter_nonenglish(df):
    new_df = None  # Do some magical operations here to create the filtered df
    return new_df

df = pd.read_csv('somecsv.csv')
df_new = filter_nonenglish(df)
print('New df is: ', df_new)

注意!其他5列是什么并不重要。 另请注意:使用detect非常简单:

t = 'I am very cool!'
print(detect(t))

输出为:

en

Tags: csv函数text文本importdfnewinput
1条回答
网友
1楼 · 发布于 2024-10-01 02:23:38

您可以在df上执行以下操作,并在input_text列中获取所有包含英文文本的行:

df_new = df[df.input_text.apply(detect).eq('en')]

因此,基本上只需将langdetect.detect函数应用于input_text列中的值,并获取所有那些文本被检测为“en”的行

相关问题 更多 >