【问题标题】:Replace dataframe entries with another dataframe (series?) entry? vectorize? compression?用另一个数据框(系列?)条目替换数据框条目?矢量化?压缩?
【发布时间】: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


【解决方案1】:

最好的方法大概是使用 Pandas 的DataFrame.replace 方法:

# The raw_data DF
df1 = pd.DataFrame({'raw_data': ['Lorem', 'ipsum', 'dolor', 'sit', 'amet,', 
                                 'consectetur', 'adipiscing', 'elit']})
print 'Original:'
print df1

# The replacement patterns DF
df2 = pd.DataFrame({'replacethis': ['ipsum', 'it'], 'withthis': ['doggy', 'THAT']})
pattern_dict = df2.set_index('replacethis')['withthis'].to_dict()

df1_replaced = df1.replace(pattern_dict, regex=True)
print '\nAfter Replacement:'
print df1_replaced

结果:

Original:
      raw_data
0        Lorem
1        ipsum
2        dolor
3          sit
4        amet,
5  consectetur
6   adipiscing
7         elit

After Replacement:
      raw_data
0        Lorem
1        doggy
2        dolor
3        sTHAT
4        amet,
5  consectetur
6   adipiscing
7       elTHAT

【讨论】:

  • 非常好,再次感谢一百万。
猜你喜欢
  • 2021-09-08
  • 1970-01-01
  • 1970-01-01
  • 2019-01-31
  • 1970-01-01
  • 1970-01-01
  • 2017-09-11
  • 1970-01-01
  • 2021-07-02
相关资源
最近更新 更多