简体   繁体   English

使用列表理解的Python部分字符串匹配

[英]Python partial string match using list comprehension

I am trying to use list comprehensions to edit a list based on partial string match. 我正在尝试使用列表推导来基于部分字符串匹配来编辑列表。 I need to replace all elements in group column of df which contains L with Left 我需要将包含L的df group列中的所有元素替换为Left

['Left' if x.str.contains('L') else x for x in df['group']]

It wont let me apply str.contains or 'L' in x . 它不会让我'L' in x应用str.contains或'L' in x For latter it says argument of type 'float' is not iterable 对于后者,它说argument of type 'float' is not iterable

Any suggestion would be welcome. 任何建议都将受到欢迎。

EDIT: ADDING DATA 编辑:添加数据

import pandas as pd
df=pd.DataFrame()
df['group']=[u'L1', u'L2', u'L3', u'R1', u'R2', u'R3']

You can cast x to a string like below 您可以将x强制转换为如下所示的字符串

['Left' if 'L' in str(x) else x for x in df['group']]

But, if x is being interpreted as a float it sounds like an issue with the data source, unless it is viable for df['group'] to contain both strings and floats? 但是,如果x被解释为浮点数,这听起来像是数据源的问题,除非df ['group']同时包含字符串和浮点数是可行的?

EDIT: 编辑:

If both floats and strings are in your data I'd suggest only looking for 'L' in the strings: 如果浮点数和字符串都在您的数据中,则建议您仅在字符串中查找“ 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM