首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用Python连接Pandas Dataframe上的文本

用Python连接Pandas Dataframe上的文本
EN

Stack Overflow用户
提问于 2016-02-02 02:41:11
回答 1查看 278关注 0票数 1

我试图沿着一行连接文本,然后按ID分组

我有一个如下所示的数据集:

代码语言:javascript
复制
data=pd.DataFrame(data={'ID':['1','1','2','2','2','3','3','3','3'],
                    'Text1':['Apple','','','Laptop','','Pens','','Ruler',''],
                    'Text2': ['Bananas','Grape','Mouse','','DVD Player','','Pencils','',''],
                    'Text3':['Cherry','','','Headphones','','','','','Eraser'],
                    'Text4':['Mango','Strawberries','','','Cell phone','','Sticky Notes','','']
                   })

data =data.set_index('ID')

ID  Text1   Text2      Text3      Text4
1   Apple   Bananas    Cherry     Mango
1           Grape                 Strawberries
2           Mouse       
2   Laptop             Headphones   
2           DVD-Player            Cell-phone
3   Pens            
3           Pencils               Sticky Notes
3   Ruler           
3           Eraser  

我想要的手术:

  1. 先串接行
  2. 按每个ID分组,以获得一组由分隔符分隔的单词。

对于如何实现这个输出,有什么想法吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-02-02 02:57:03

我建议使用DataFrame.groupbyDataFrame.applystr.join的一些组合。根据您提供的内容,您可以使用以下内容。以下只是一个例子。

代码语言:javascript
复制
import pandas as pd
import re

data = pd.DataFrame(data={'ID':['1','1','2','2','2','3','3','3','3'],
                    'Text1':['Apple','','','Laptop','','Pens','','Ruler',''],
                    'Text2': ['Bananas','Grape','Mouse','','DVD Player','','Pencils','',''],
                    'Text3':['Cherry','','','Headphones','','','','','Eraser'],
                    'Text4':['Mango','Strawberries','','','Cell phone','','Sticky Notes','','']
                    })


cols = [x for x in data.columns if re.search("^Text", x)] # list of all columns
                                                          # that start with "Text"

# function to be applied that takes a row and a list of columns 
# to concatenate
def concat_text(row, cols):
    # The real work is done here
    return ";".join([";".join([str(x) for x in y if x]) for y in row[cols].values])

result = data.groupby("ID").apply(concat_text, cols) # groupby and apply

这会给你留下

代码语言:javascript
复制
ID
1    Apple;Bananas;Cherry;Mango;Grape;Strawberries
2    Mouse;Laptop;Headphones;DVD Player;Cell phone
3           Pens;Pencils;Sticky Notes;Ruler;Eraser
dtype: object
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35144121

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档