Split a text(with names and values) column into multiple columns in Pandas DataFrame

爷,独闯天下 提交于 2021-01-28 02:51:09

问题


I have problem with speed of my algorithm, is too slow. I have a big dataframe and wanna create columns depends on the name and value in other. I am looking for a solution maybe in Pandas. Before running I don't know the size of the future columns. Here is a simple schema.

"column"<==>"value"<br>"column"<==> "value"<br>...

my data frame

id |     params     |
---|-----------------
0  |currency<=>PLN<br>price<=>72.14<br>city<==>Berlin
---|-----------------
1  |price<=>90<br>area<=>72.14<br>city<==>San Francisco<br>rooms<==>2<br>is_Free<==>1
---|-----------------

And i would like to have something like this

   id | price | currency |      city    | rooms | is_Free| area|
   ---|------ |----------|--------------|-------|--------|------
     0| 72.14 |  PLN     |     Berlin   |  NaN  |   NaN  |  NaN|
   ---|-------|----------|--------------|-------|--------|------
     1|  90   |  NaN     | San Francisco|   2   |    1   |  90 |

My solution:

def add_parameters(df):
    for i,row in df.iterrows():
        parameters_list = row.params.split("<br>")
        for parameter in parameters_list:
            elem_list = parameter.split("<=>")
            if elem_list[0]  and elem_list[1] != '':
                df.loc[i, elem_list[0]] = elem_list[1]
    return df

Thanks


回答1:


This is one way of approaching the problem.

import re

# handle multiple seperator.
sep = re.compile(r"(<.*>)")


def split(value):
    ret = {}
    for s in value.split("<br>"):
        # search if seperator exists in the string & split based on sep.
        if sep.search(s):
            split_ = s.split(sep.search(s).group())
            ret[split_[0]] = split_[1]

    return ret

print(df['params'].apply(lambda x : split(x)).apply(pd.Series))

Output

  currency  price           city   area rooms is_Free
0      PLN  72.14         Berlin    NaN   NaN     NaN
1      NaN     90  San Francisco  72.14     2       1



回答2:


If you would like to do it in one line with list comp (but i am not sure if it is readable tho):

pattern = re.compile(r"<=*>")
df = df['params'].apply(lambda row: dict([pattern.split(kv) for kv in row.split("<br>")])).apply(pd.Series)


来源:https://stackoverflow.com/questions/61973170/split-a-textwith-names-and-values-column-into-multiple-columns-in-pandas-dataf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!