【发布时间】:2016-08-19 03:57:24
【问题描述】:
我定义了一个函数来执行我想要的任务,但是速度非常慢。对于带有标题'raw_data' 的DataFrame (df1=pd.read(file1)),我目前使用.iterows 循环遍历每个字符串,并将每个条目发送到一个函数,该函数剥离和降低然后使用str.replace(row['replacethis'],row['withthis']),其中'replacethis' 和'withthis' 是a 中的列第二个DataFrame ((df2=pd.read(file2))。
但是,这非常慢,需要几天才能处理 file1/file2 的大量元素。我一直在寻找解决方案几个小时/天,我尝试使用 series.str.replace 进行列表压缩,但无济于事:
'raw_data'=[[x['raw_data'].replace(y['replacethis'],y['withthis']) for y in df2.iterrows()] for x in df1.iterrows()]
谁能提供任何指导或建议?这让我发疯了。
【问题讨论】:
-
在剥离和小写后,字符串是否完全匹配
replacethis还是只包含replacethis字符串内容? -
对于函数的一个版本,它是完全匹配的(我在函数中使用 if str == row['raw_data']),对于某些版本,它是一个子字符串...
-
那么对于子字符串部分,您是否期望 1 个或多个匹配项以及完全匹配项?对于精确匹配,您可以只在这些列上使用
merge,另一方面,我认为除了迭代和使用str.contains或类似方法之外,您无能为力 -
你能提供一个例子和你想要的输出吗?
-
(它们都是系列并且函数循环通过它们:) 对于子字符串示例:'raw_data' 是“坐在垫子上的猫”,'replacethis' 是“猫”,'withthis ' 是“狗”,期望的输出:“狗坐在垫子上”。但是,df2 中的这两个列表可以有多个替换。对于完整的字符串匹配: 'raw_data': "The cat sat on the mat", 'replacethis' 是 "The cat sat on the mat", 'withthis' 是 "The dog sat on the mat", 期望的输出是 "The狗坐在垫子上”
标签: python list pandas replace dataframe