首页 > 解决方案 > 从 sql 响应中提取值

问题描述

我目前正在整理一个熊猫数据框。为此,我查询我的 sql 以准备数据。

    mycursor.execute("select post_id,meta_value from wp_postmeta where meta_key = 'berufsgruppe' and post_id = %s",[id])
df_berufsgruppe=pd.DataFrame(data=mycursor.fetchall(), columns=['post_id','berufsgruppe'])

以下值包含在几个地方的 sql 中。我必须做什么才能获得价值?

a:1:{i:0;s:10: "employed";}
a:1:{i:0;s:5:"Miete";}
a:1:{i:0;s:2:"ja";}

我需要“就业

非常感谢您的支持!

标签: pythonpandas

解决方案


你的df样子是这样的吗?

                  berufsgruppe
0  a:1:{i:0;s:10: "employed";}
1       a:1:{i:0;s:5:"Miete";}
2          a:1:{i:0;s:2:"ja";}

如果是这样,那么您可以使用.str.extract().

df['value'] = df['berufsgruppe'].str.extract(r'.+"(.+)".+')
print(df)

                  berufsgruppe     value
0  a:1:{i:0;s:10: "employed";}  employed
1       a:1:{i:0;s:5:"Miete";}     Miete
2          a:1:{i:0;s:2:"ja";}        ja

推荐阅读