为与正则表达式模式匹配的数据帧分配特定的 id

需要为每个符合以下条件的数据帧分配一个特定的ID


fd = df[(df['B'].str.match('.*Color:.*') | df['B'].str.match('.*colorFUL:.*')) & df.A.isnull()]

fd2 = df[(df['B'].str.match('.*Type:.*')) & df.A.isnull()]

在输出文件中,两个数据帧都被写在另一个数据帧的下面。需要添加列 C,其中 ID“1”分配给 fd,ID“2”分配给 fd2。这将有助于过滤数据帧。


这是当前的输出


A   B

nan this has Color:Red

nan Color: Blue,red, green

nan Color: Yellow

nan This has many colors. Color: green, red, Yellow

nan Filter oil Type: Synthetic Motor oil

nan Oil Type : High Mileage Motor oil

预期输出


A   B   C

nan this has Color:Red  1

nan Color: Blue,red, green  1

nan Color: Yellow   1

nan This has many colors. Color: green, red, Yellow 1

nan Filter oil Type: Synthetic Motor oil    2

nan Oil Type : High Mileage Motor oil   2


慕雪6442864
浏览 78回答 1
1回答

慕田峪4524236

添加新列 C 并根据与正则表达式匹配的数据帧为该列分配 ID“1”或“2”。In [17]: dfOut[17]:     A                                                B0 NaN                               this has Color:Red1 NaN                           Color: Blue,red, green2 NaN                                    Color: Yellow3 NaN  This has many colors. Color: green, red, Yellow4 NaN             Filter oil Type: Synthetic Motor oil5 NaN                Oil Type : High Mileage Motor oil您构造了两个条件:In [18]: one = (df['B'].str.match('.*Color:.*') | df['B'].str.match('.*colorFUL:.*')) & df.A.isnull()In [19]: oneOut[19]: 0     True1     True2     True3     True4    False5    Falsedtype: boolIn [20]: two = (df['B'].str.match('.*Type:.*')) & df.A.isnull()In [21]: twoOut[21]: 0    False1    False2    False3    False4     True5    Falsedtype: bool这是制作新专栏的一种方法。In [22]: df['C'] = 0使用条件的布尔系列根据这些条件分配值。In [23]: df.loc[one,'C'] = 1In [24]: df.loc[two,'C'] = 2In [25]: dfOut[25]:     A                                                B  C0 NaN                               this has Color:Red  11 NaN                           Color: Blue,red, green  12 NaN                                    Color: Yellow  13 NaN  This has many colors. Color: green, red, Yellow  14 NaN             Filter oil Type: Synthetic Motor oil  25 NaN                Oil Type : High Mileage Motor oil  0如果 df 是输入数据帧,fd 是与模式匹配的输出数据帧,如何直接将 id 分配给 fd 而不进行布尔检查fd = df.loc[one]fd['C'] = 1
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python