我有两个 Dataframedf1
看起来像这样(相关列):
brand product_line size profile
0 winter hdw2 21.r LINEN
1 stone r294 31x5 WAXY
2 han th22 3t NaN
3 winter trjj 5t LINEN
4 stone ael2 2d LINEN
我有另一个dataframe,它有许多列,下面是相关的列:
df2
NAME PRODUCT_LINE SIZE MAKE
0 winter+ hdw2 21.r 0.2
1 stoneas r294 31x5 0.5
2 han th22 3t 3
3 winter trjj 5t 1
4 stone ael2 2d 34
现在基本上第一个框架中的列分别Map到NAME
、PRODUCT_LINE
和SIZE
。两个帧中的列都是str.lower()
和str.replace(" ", "")
现在,我希望MAKE
列在第一个嵌套框中,这样这个条件对所有行都应该为真。我可以一行一行地做,但要花很多时间。有没有一种方法可以在整个列上快速完成,而不需要在 Dataframe 中循环?我想要一个有效的解决方案。
下面是我如何在循环中做到这一点:
spec = df2[(df2['NAME'].str.lower().str.replace(' ', '').str.contains(row.brand.lower().replace(' ', '')))
& (df2['PRODUCT_NAME'].str.lower().str.replace(' ', '').str.contains(row.product_line.lower().replace(' ', '')))
& (df2['SIZE'].str.lower().str.replace(' ', '').str.contains(row.size.lower().replace(' ', ''))) ]
所以基本上,当上面的条件对一行为真时,它应该从df2
中获取相应的MAKE并放入df1
中。而且,只有当df1
中的profile
列不是NaN
时,才会发生这种情况。
1条答案
按热度按时间vlju58qv1#
为了提高效率,我建议
merging
水平的两个嵌套框来处理一个嵌套框。此外,由于您只希望在所有条件都满足的情况下检索MAKE值,如果其中一个条件不满足,那么比较观察的其他项就没有意义了。这可以保存你很多时间。因此,我引入了一个
list_indices
变量,它将比较限制为仅对这些值进行比较。下面是完整的代码:
结果如下:
| | 产品线|大小|轮廓|使| MAKE |
| --|--|--|--|--|--|
| 0 |冬季|HDW2| 21.r|亚麻|0.2|
| 1 |石|r294| 31x5|蜡质|0.5|
| 2 |韩|th22| 3t|楠|楠|
| 3 |冬季|特里季|5t|亚麻| 1 |
| 4 |石|AEL2| 2d|亚麻| 34 |
让我知道这是否符合你的要求!