![](/img/trans.png)
[英]How to find the maximum value of a column/row combination in a concatenated dataframe in Pandas
[英]how to find the english and chinese combination records in pandas dataframe
在 Pandas 中,数据框有 2 列,如“FirstName”和“LastName”。 从该列中,“名字”列将是英文或中文组合,与“姓氏”列相同,将是中文或英文组合。 所以,我想在数据框中显示那些英汉组合的记录。
code snippet:
df.loc[df['FirstName'].str.contains(r'[a-zA-Z]+') & df['FirstName'].str.contains(r'[一种-ž]+'))]
我不知道这个代码片段是否有效。
我的输入数据框是:
FirstName LastName
jocovich nadhal
smith pointing
西德哈斯 supreet
yuvi 雷迪
bsreddy rakshita
sreeja 巴尔加维
雷迪 西德哈斯
Cédric LEMARCHAND
Radosław Piotrowski
上面是我的数据框。 但我需要的输出如下:
FirstName LastName
西德哈斯 supreet
yuvi 雷迪
sreeja 巴尔加维
我想显示数据框中的英文-中文或中文-英文记录。
您可以像我在这里一样搜索 unicode。 您也可以反转匹配:
df.query("FirstName.str.contains(r'[\u4e00-\u9FFF]', regex=True) or LastName.str.contains(r'[\u4e00-\u9FFF]', regex=True)")
or
df[(df['FirstName'].str.contains(r'[\u4e00-\u9FFF]', regex=True)) | ( df['LastName'].str.contains(r'[\u4e00-\u9FFF]', regex=True))]
或者不匹配中文名字和姓氏:
df[((df['FirstName'].str.contains(r'[\u4e00-\u9FFF]', regex=True)) | ( df['LastName'].str.contains(r'[\u4e00-\u9FFF]', regex=True))) & (~df['FirstName'].str.contains(r'[\u4e00-\u9FFF]', regex=True) | (~df['LastName'].str.contains(r'[\u4e00-\u9FFF]', regex=True)))]
输出:
FirstName LastName
2 西德哈斯 supreet
3 yuvi 雷迪
5 sreeja 巴尔加维
试试这个,逻辑只是检查字符串是否只能用 ASCII 字符编码。
# -*- coding: utf-8 -*-
df = pd.DataFrame({"FirstName":["jocovich","smith"," 西德哈斯","yuvi"," bsreddy","sreeja"],"LastName":["nadhal","pointing","supreet","雷迪","rakshita","巴尔加维"],"blah":["example","example","example","example","example","example"]})
def isEnglish(s):
o = list(s)
ot = []
for n in o:
try:
n.encode(encoding='utf-8').decode('ascii')
except UnicodeDecodeError:
ot.append(False)
else:
ot.append(True)
if ot==[True,False] or ot == [False,True]:
return True
else:
return False
output = df[df[["FirstName","LastName"]].apply(lambda x: isEnglish(x),axis=1)]
输出
FirstName LastName blah
2 西德哈斯 supreet example
3 yuvi 雷迪 example
5 sreeja 巴尔加维 example
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.