繁体   English   中英

根据条件从另一个数据框设置数据框列的值

[英]Setting value for dataframe column from another dataframe based on condition

我有一个数据框

#Around 100000 rows
df = pd.DataFrame({'text':    [ 'Apple is healthy',  'Potato is round', 'Apple might be green'],
                   'category': ["","", ""],
                   })

第二个数据框

#Around 3000 rows
df_2 = pd.DataFrame({'keyword':    [ 'Apple ',  'Potato'],
                   'category': ["fruit","vegetable"],
                   })

需要的结果

#Around 100000 rows
df = pd.DataFrame({'text':    [ 'Apple is healthy',  'Potato is round', 'Apple might be green'],
                   'category': ["fruit","vegetable", "fruit"],
                   })

我目前试过这个

df.set_index('text')
df_2.set_index('keyword')
df.update(df_2)

结果是

text    category
Apple is healthy    fruit
Potato is round vegetable
Apple might be green

如您所见,它没有为最后一行添加类别。 我怎样才能做到这一点?

您需要从DataFrame.set_index分配回输出,因为不是像DataFrame.update这样的就地操作,用于匹配的Series.str.extract按列df_2["keyword"]

df = df.set_index(df['text'].str.extract(f'({"|".join(df_2["keyword"])})', expand=False))
df_2 = df_2.set_index('keyword')
print (df)
                        text category
text                                 
Apple       Apple is healthy         
Potato       Potato is round         
Apple   Apple might be green  



df.update(df_2)
print (df)
                        text   category
text                                   
Apple       Apple is healthy      fruit
Potato       Potato is round  vegetable
Apple   Apple might be green      fruit

如果只需要添加一列,请使用Series.str.extractSeries.map

s = df['text'].str.extract(f'({"|".join(df_2["keyword"])})', expand=False)
df['category'] = s.map(df_2.set_index(['keyword'])['category'])
print (df)
                   text   category
0      Apple is healthy      fruit
1       Potato is round  vegetable
2  Apple might be green      fruit

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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