如何将一个数据框列中的多个键值对的字符串分解为python中的新数据框?

时间:2019-05-17 02:14:42

标签: python pandas dataframe

我正在将数据从sql数据库拉入pandas数据框。数据帧是一个单列,其中包含存储在字符串中的各种数量的键值对。我想制作一个新的数据框,其中包含两列,一列保存键,另一列保存值。

数据框如下:

In[1]:
print(df.tail())

Out[1]:
WK_VAL_PAIRS
166  {('sloth', 0.073), ('animal', 0.034), ('gift', 0.7843)}                              
167  {('dabbing', 0.0863), ('gift', 0.7843)}      
168  {('grandpa', 0.0156), ('funny', 1.3714), ('grandfather', 0.0015)}                                     
169  {('nerd', 0.0216)}
170  {('funny', 1.3714), ('pineapple', 0.0107)} 

理想情况下,新的数据框如下所示:

0  |  sloth    |  0.073
1  |  animal   |  0.034
2  |  gift     |  0.07843
3  |  dabbing  |  0.0863
4  |  gift     |  0.7843
...
etc.

我成功地将键值对从单行中分离到一个数据帧中,如下所示。从这里开始,将两对分成自己的列将很简单。

In[2]:
def prep_text(row):
    string = row.replace('{', '')
    string = string.replace('}', '')
    string = string.replace('\',', '\':')
    string = string.replace(' ', '')
    string = string.replace(')', '')
    string = string.replace('(', '')
    string = string.replace('\'', '')
    return string

df['pairs'] = df['WK_VAL_PAIRS'].apply(prep_text)
dd = df['pairs'].iloc[166]
af = pd.DataFrame([dd.split(',') for x in dd.split('\n')])
af.transpose()

Out[2]:

0   sloth:0.073
1   animal:0.034
2   gift:0.7843
3   spirit:0.0065
4   fans:0.0093
5   funny:1.3714

但是,我没有将这种转换应用于整个数据框的飞跃。有没有一种方法可以使用.apply()样式函数而不是for each循环来做到这一点。处理此问题的最有效方法是什么?

任何帮助将不胜感激。

解决方案

在下面克里斯的强烈提示下,我能够找到满足自己需求的适当解决方案:

def prep_text(row):
    string = row.replace('\'', '')
    string = '"'+ string + '"'
    return string


kvp_df = pd.DataFrame(
                        re.findall(
                            '(\w+), (\d.\d+)', 
                            df['WK_VAL_PAIRS'].apply(prep_text).sum()
                        )
                    )

1 个答案:

答案 0 :(得分:2)

尝试re.findallpandas.DataFrame

import pandas as pd
import re

s = pd.Series(["{(stepper, 0.0001), (bob, 0.0017), (habitual, 0.0), (line, 0.0097)}",
"{(pete, 0.01), (joe, 0.0019), (sleep, 0.0), (cline, 0.0099)}"])

pd.DataFrame(re.findall('(\w+), (\d.\d+)', s.sum()))

输出:

          0       1
0   stepper  0.0001
1       bob  0.0017
2  habitual     0.0
3      line  0.0097
4      pete    0.01
5       joe  0.0019
6     sleep     0.0
7     cline  0.0099