将列表列表转换为字符串pandas dataframe [英] turn lists of lists into strings pandas dataframe

查看:1345
本文介绍了将列表列表转换为字符串pandas dataframe的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

背景

我有以下玩具df,该玩具在BeforeAfter列中包含列表,如下所示

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

输出

                    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

此输出很接近,但与我要查找的输出不完全相同,因为当我想要的输出看起来像这样时,AfterBefore列只有一个单词输出(例如there):

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:

所需的输出

     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

问题

如何获取我的期望的输出?

推荐答案

agg + join.逗号不在列表中,只是列表__repr__的一部分.

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)

这篇关于将列表列表转换为字符串pandas dataframe的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆