熊猫拆分列

2024-01-07

给定以下数据框:

import pandas as pd
import numpy as np
df = pd.DataFrame({
       'A' : ['a', 'b','c', 'd'],
       'B' : ['Y>`abcd', 'abcd','efgh', 'Y>`efgh']
    })
df

    A   B
0   a   Y>`abcd
1   b   abcd
2   c   efgh
3   d   Y>`efgh

我想将 '>`' 上的 A 列分成 2 列(C 和 D),这样我的数据

frame looks like this:
        A   C  D
    0   a   Y  abcd
    1   b      abcd
    2   c      efgh
    3   d   Y  efgh

提前致谢!


您可以使用str.extract http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.extract.html with fillna http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.fillna.html,最后一滴列B by drop http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.drop.html:

df[['C','D']] = df['B'].str.extract('(.*)>`(.*)', expand=True)
df['D'] = df['D'].fillna(df['B'])
df['C'] = df['C'].fillna('')
df = df.drop('B', axis=1)

print df

   A  C     D
0  a  Y  abcd
1  b     abcd
2  c     efgh
3  d  Y  efgh

下一个解决方案使用str.split http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.split.html with mask and numpy.where http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.where.html:

df[['C','D']] =  df['B'].str.split('>`', expand=True) 
mask = pd.notnull(df['D'])
df['D'] = df['D'].fillna(df['C'])
df['C'] = np.where(mask, df['C'], '')
df = df.drop('B', axis=1) 

Timings:

很大DataFrame is extract解决方案100快几倍,小1.5 times:

len(df)=4:

In [438]: %timeit a(df)
100 loops, best of 3: 2.96 ms per loop

In [439]: %timeit b(df1)
1000 loops, best of 3: 1.86 ms per loop

In [440]: %timeit c(df2)
The slowest run took 4.44 times longer than the fastest. This could mean that an intermediate result is being cached 
1000 loops, best of 3: 1.89 ms per loop

In [441]: %timeit d(df3)
The slowest run took 4.62 times longer than the fastest. This could mean that an intermediate result is being cached 
1000 loops, best of 3: 1.82 ms per loop

len(df)=4k:

In [443]: %timeit a(df)
1 loops, best of 3: 799 ms per loop

In [444]: %timeit b(df1)
The slowest run took 4.19 times longer than the fastest. This could mean that an intermediate result is being cached 
100 loops, best of 3: 7.37 ms per loop

In [445]: %timeit c(df2)
1 loops, best of 3: 552 ms per loop

In [446]: %timeit d(df3)
100 loops, best of 3: 9.55 ms per loop

Code:

import pandas as pd
df = pd.DataFrame({
       'A' : ['a', 'b','c', 'd'],
       'B' : ['Y>`abcd', 'abcd','efgh', 'Y>`efgh']
    })
#for test 4k    
df = pd.concat([df]*1000).reset_index(drop=True)
df1,df2,df3 = df.copy(),df.copy(),df.copy()

def b(df):
    df[['C','D']] = df['B'].str.extract('(.*)>`(.*)', expand=True)
    df['D'] = df['D'].fillna(df['B'])
    df['C'] = df['C'].fillna('')
    df = df.drop('B', axis=1)
    return df

def a(df):
    df = pd.concat([df, df.B.str.split('>').apply(
    lambda l: pd.Series({'C': l[0], 'D': l[1][1: ]}) if len(l) == 2 else \
        pd.Series({'C': '', 'D': l[0]}))], axis=1)
    del df['B']
    return df

def c(df):
    df[['C','D']] = df['B'].str.split('>`').apply(lambda x: pd.Series(['']*(2-len(x)) + x))
    df = df.drop('B', axis=1)    
    return df   

def d(df):
    df[['C','D']] =  df['B'].str.split('>`', expand=True) 
    mask = pd.notnull(df['D'])
    df['D'] = df['D'].fillna(df['C'])
    df['C'] = np.where(mask, df['C'], '')
    df = df.drop('B', axis=1) 
    return df  
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

熊猫拆分列 的相关文章

随机推荐