превратить списки списков в строки pandas dataframe - PullRequest
3 голосов
/ 07 июля 2019

Фон

У меня есть следующая игрушка df, которая содержит списки в столбцах Before и After, как показано ниже

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']
                 })

Вывод

                    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

Проблема

Использование следующего блока кода:

df.loc[:, ['After', 'Before']] = df[['After', 'Before']].apply(lambda x: x.str[0].str.replace(',', '')) взято из Удалениезапятые и распечатка кадра данных производят следующий вывод:

Вывод "почти то, что я хочу, но не совсем"

    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

Этот вывод близок, но не совсем то, что я ищу, потому что столбцы After и Before имеют только одно выходное слово (например, there), когда мой желаемый вывод выглядит так:

Требуемый вывод

     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

Вопрос

Как получить Желаемый вывод ?

Ответы [ 3 ]

4 голосов
/ 07 июля 2019

agg + join. Запятых нет в ваших списках, они просто являются частью __repr__ списка.


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

Если вы предпочитаете на месте (быстрее):

df[str_cols] = df.agg(d)
3 голосов
/ 07 июля 2019

applymap

В очереди

Новая копия кадра данных с желаемыми результатами

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

На месте

Мутировать существующее 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 и str.join

Мы можем использовать этот результат аналогично «In line» и «In place», как показано выше.

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
2 голосов
/ 07 июля 2019

Мы можем указать списки, которые мы хотим преобразовать в строку, а затем использовать .apply в цикле for:

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
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...