Python,在列中拆分多个字符串

标签 python pandas numpy dataframe text

下午好,我正在尝试将列中的文本拆分为特定格式 这是我的下表

UserId  Application
1       Grey Blue::Black Orange;White:Green
2       Yellow Purple::Orange Grey;Blue Pink::Red

我希望它读取以下内容:

UserId  Application
    1       Grey Blue
    1       White Orange
    2       Yellow Purple
    2       Blue Pink

基本上,我想保留给定单元格中每个字符串的每个::实例的第一个字符串。

到目前为止我的代码是

def unnesting(df, explode):
    idx=df.index.repeat(df[explode[0]].str.len())
    df1=pd.concat([pd.DataFrame({x:np.concatenate(df[x].values)} )for x in explode],axis=1)
    df1.index=idx
    return df1.join(df.drop(explode,1),how='left')

df['Application']=df.Role.str.split(';|::|').map(lambda x : x[0::2])

unnesting(df.drop('Role',1),['Application']

下面的代码读取

UserId  Application
        1       Grey Blue, White Orange
        2       Yellow Purple, Blue Pink

请帮忙,我不知道应该在哪里使用 pandas 或 numpy 来解决这个问题!!

最佳答案

也许你可以尝试使用extractall

yourdf=df.set_index('UserId').Application.str.extractall(r'(\w+):').reset_index(level=0) 
# You can adding rename(columns={0:'Application'})at the end
Out[87]: 
       UserId       0
match                
0           1    Grey
1           1   White
0           2  Yellow
1           2    Blue
<小时/>

更新查看 unnesting ,在我们分割并从字符串中选择我们需要的值之后,我们将它们存储到list中,当你有一个list类型时columns ,我建议使用 unnesting

df['LIST']=df.Application.str.split(';|::|:').map(lambda x : x[0::2])

unnesting(df.drop('Application',1),['LIST'])
Out[111]: 
            LIST  UserId
0      Grey Blue       1
0          White       1
1  Yellow Purple       2
1      Blue Pink       2
<小时/>

我自己的定义函数

def unnesting(df, explode):
    idx=df.index.repeat(df[explode[0]].str.len())
    df1=pd.concat([pd.DataFrame({x:np.concatenate(df[x].values)} )for x in explode],axis=1)
    df1.index=idx
    return df1.join(df.drop(explode,1),how='left')

关于Python,在列中拆分多个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55081439/

相关文章:

python - 通过 Scipy 和 Numpy 使用 Python 将数据拟合到 ODE 系统

Python,奇怪的内存消耗行为

python - 在 Pandas 数据框中分隔 'networks'

python:我可以在不(明确)使用整数索引的情况下获得稀疏矩阵表示吗?

python - Pandas:删除列级别并合并标题

python - 在 python 中使用 (in) 关键字测试字符串成员身份非常慢

python - Numpy 屏蔽数组 argmax 在完全屏蔽数组上不返回 'masked'?

python - 内存高效的最近邻算法

python - 如何将动态页码插入到添加的幻灯片中?

python - Windows 和 ZMQ 上的 CX_Freeze 导入错误