turn lists of lists into strings pandas dataframe

落爺英雄遲暮 提交于 2019-12-12 18:52:18

问题


Background

I have the following toy df that contains lists in the columns Before and After as seen below

import pandas as pd
before = [list(['in', 'the', 'bright', 'blue', 'box']), 
       list(['because','they','go','really','fast']), 
       list(['to','ride','and','have','fun'])]
after = [list(['there', 'are', 'many', 'different']), 
       list(['i','like','a','lot','of', 'sports']), 
       list(['the','middle','east','has','many'])]

df= pd.DataFrame({'Before' : before, 
                   'After' : after,
                  'P_ID': [1,2,3], 
                  'Word' : ['crayons', 'cars', 'camels'],
                  'N_ID' : ['A1', 'A2', 'A3']
                 })

Output

                    After                Before                     N_ID P_ID   Word
0   [in, the, bright, blue, box]        [there, are, many, different]   A1  1   crayons
1   [because, they, go, really, fast]   [i, like, a, lot, of, sports ]  A2  2   cars
2   [to, ride, and, have, fun]        [the, middle, east, has, many]    A3  3   camels

Problem

Using the following block of code:

df.loc[:, ['After', 'Before']] = df[['After', 'Before']].apply(lambda x: x.str[0].str.replace(',', '')) taken from Removing commas and unlisting a dataframe produce the following output:

Close-to-what-I-want-but-not-quite- Output

    After   Before  N_ID  P_ID  Word
0   in      there    A1    1    crayons
1   because  i       A2    2    cars
2   to      the      A3    3    camels

This output is close but not quite what I am looking for because After and Before columns have only one word outputs (e.g. there) when my desired output looks as such:

Desired Output

     After                           Before               N_ID  P_ID  Word
0 in the bright blue box        there are many different  A1    1   crayons
1 because they go really fast   i like a lot of sports    A2    2   cars
2 to ride and have fun         the middle east has many   A3    3   camels

Question

How do I get my Desired Output?


回答1:


agg + join. The commas aren't present in your lists, they are just part of the __repr__ of the list.


str_cols = ['Before', 'After']

d = {k: ' '.join for k in str_cols}

df.agg(d).join(df.drop(str_cols, 1))

                        Before                     After  P_ID     Word N_ID
0       in the bright blue box  there are many different     1  crayons   A1
1  because they go really fast    i like a lot of sports     2     cars   A2
2         to ride and have fun  the middle east has many     3   camels   A3

If you'd prefer in place (faster):

df[str_cols] = df.agg(d)



回答2:


applymap

In line

New copy of a dataframe with desired results

df.assign(**df[['After', 'Before']].applymap(' '.join))

                        Before                     After  P_ID     Word N_ID
0       in the bright blue box  there are many different     1  crayons   A1
1  because they go really fast    i like a lot of sports     2     cars   A2
2         to ride and have fun  the middle east has many     3   camels   A3

In place

Mutate existing df

df.update(df[['After', 'Before']].applymap(' '.join))
df

                        Before                     After  P_ID     Word N_ID
0       in the bright blue box  there are many different     1  crayons   A1
1  because they go really fast    i like a lot of sports     2     cars   A2
2         to ride and have fun  the middle east has many     3   camels   A3

stack and str.join

We can use this result in a similar "In line" and "In place" way as shown above.

df[['After', 'Before']].stack().str.join(' ').unstack()

                      After                       Before
0  there are many different       in the bright blue box
1    i like a lot of sports  because they go really fast
2  the middle east has many         to ride and have fun



回答3:


We can specify the lists we want to convert to string and then use .apply in a for loop:

lst_cols = ['Before',  'After']

for col in lst_cols:
    df[col] = df[col].apply(' '.join)
                        Before                     After  P_ID     Word N_ID
0       in the bright blue box  there are many different     1  crayons   A1
1  because they go really fast    i like a lot of sports     2     cars   A2
2         to ride and have fun  the middle east has many     3   camels   A3


来源:https://stackoverflow.com/questions/56918887/turn-lists-of-lists-into-strings-pandas-dataframe

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