[英]Python partial string match using list comprehension
我正在嘗試使用列表推導來基於部分字符串匹配來編輯列表。 我需要將包含L
的df group
列中的所有元素替換為Left
['Left' if x.str.contains('L') else x for x in df['group']]
它不會讓我'L' in x
應用str.contains或'L' in x
。 對於后者,它說argument of type 'float' is not iterable
任何建議都將受到歡迎。
編輯:添加數據
import pandas as pd
df=pd.DataFrame()
df['group']=[u'L1', u'L2', u'L3', u'R1', u'R2', u'R3']
您可以將x強制轉換為如下所示的字符串
['Left' if 'L' in str(x) else x for x in df['group']]
但是,如果x被解釋為浮點數,這聽起來像是數據源的問題,除非df ['group']同時包含字符串和浮點數是可行的?
編輯:
如果浮點數和字符串都在您的數據中,則建議您僅在字符串中查找“ L”:
['Left' if isinstance(x, unicode) and u'L' in x else x for x in df['group']]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.