首页 > 解决方案 > 使用 pandas 现有列中的信息创建动态列

问题描述

我有这个数据框

dd = pd.DataFrame({'text':["random text with pol # as 111 and ein no as 101",
                           "random text with pol # as 222",
                           "random text with ein # as 333 and ein no as 303"],
                   'label':[
                           [[26,29,"pol"],[44,47,"ein"]],
                           [[26,29,"pol"]],
                           [[26,29,"ein"],[44,47,"ein"]] ]})

给出这个输出

                                              text                      label
0  random text with pol # as 111 and ein no as 101  [[26,29,pol],[44,47,ein]]
1                    random text with pol # as 222               [[26,29,pol]
2  random text with ein # as 333 and ein no as 303  [[26,29,ein],[44,47,ein]]

我想要这个输出

                                              text                      label  \
0  random text with pol # as 111 and ein no as 101  [[26,29,pol],[44,47,ein]]   
1                    random text with pol # as 222               [[26,29,pol]   
2  random text with ein # as 303 and ein no as 304  [[26,29,ein],[44,47,ein]]   

   pol ein_1 ein_2  
0  111   101        
1  222              
2        303   304  

我想使用列信息动态创建列label,其中该列是列表的列表,其中一个列表包含 start_index 、 end_index 、 label_type 。通过使用开始和结束索引访问列中的文本,text我们可以获得实际的标签。

例如text:“pol # 为 222 的随机文本”并且label是 '[[26,29,pol]'

所以 pol = Text[26:29] 这是 pol = 222

所以我必须创建 pol 作为列名并将其值设为 222。

到目前为止我可以想出这个

dd["pol"] = dd.apply(lambda row: row.text[ row.label[0][0] : row.label[0][1]], axis=1)

这仅适用于数据是静态的并且每次所有数据标签都出现在同一个位置一次的情况下。

标签: pythonpandas

解决方案


我只能分几步完成

dd_tmp = dd.text.str.extractall(r"(pol|ein) (?:#|no) as (\d+)")

哪个输出

           0    1
  match
0 0      pol  111
  1      ein  101
1 0      pol  222
2 0      ein  333
  1      ein  303

然后,一步一步

dd_tmp.columns = ["name", "value"]
dd_tmp = dd_tmp.reset_index()
dd_tmp["name"] = dd_tmp["name"] + "_" + dd_tmp["match"].astype(str)
dd_tmp = dd_tmp.pivot(columns="name", index="level_0", values="value")

并且当与原始数据框连接时(on未指定,因此按索引连接)

>>> dd.join(dd_tmp)
                                              text                           label ein_0 ein_1 pol_0
0  random text with pol # as 111 and ein no as 101  [[26, 29, pol], [44, 47, ein]]   NaN   101   111
1                    random text with pol # as 222                 [[26, 29, pol]]   NaN   NaN   222
2  random text with ein # as 333 and ein no as 303  [[26, 29, ein], [44, 47, ein]]   333   303   NaN

推荐阅读