pandas dataframe column包含逗号的字符串如何将其转换为列表

时间:2017-05-08 17:24:25

标签: python pandas dataframe

数据框中的列的值为'abc,def,ghi'。我想制作一个这样的数组:['abc','def','ghi']

2 个答案:

答案 0 :(得分:1)

使用str.split

df = pd.DataFrame({'col':['abc,def,ghi','abc,def,ghi']})
df['col'] = df['col'].str.split(',')
print (df)
               col
0  [abc, def, ghi]
1  [abc, def, ghi]

print (df.loc[0, 'col'])
['abc', 'def', 'ghi']

print (type(df.loc[0, 'col']))
<class 'list'>

样品:

NaN

如果从不df['col'] = [x.split(',') for x in df['col'].values.tolist()] print (df) col 0 [abc, def, ghi] 1 [abc, def, ghi] 值使用列表理解:

CELL

答案 1 :(得分:1)

考虑数据帧df,其中字符串的随机数以逗号分隔。

np.random.seed([3,1415])
k = 10
df = pd.DataFrame(
    np.random.choice(list('ABCD,'), (k, 20))
).sum(1).str.strip(',').str.replace(',+', ',').to_frame('col1')
df

                   col1
0  ADCDCCDCDACAA,ACCA,B
1      DC,DDD,DBDA,CCAC
2    A,B,CCAC,DB,C,CD,D
3   ADDBAA,DA,BD,C,AACA
4   DADBB,D,DBD,ADCAADB
5  CBCBA,CA,B,AA,CDCBDB
6  BD,D,DDB,AC,B,C,ABBA
7  C,CABBBADCD,DBCC,ACD
8    CC,A,BCAAAACBBA,BD
9  AC,A,ADBBD,BDCCDDABD

我喜欢使用numpy功能进行拆分

df.assign(col1=np.core.defchararray.split(df.col1.values.astype(str), ','))

                           col1
0      [ADCDCCDCDACAA, ACCA, B]
1         [DC, DDD, DBDA, CCAC]
2    [A, B, CCAC, DB, C, CD, D]
3     [ADDBAA, DA, BD, C, AACA]
4      [DADBB, D, DBD, ADCAADB]
5    [CBCBA, CA, B, AA, CDCBDB]
6  [BD, D, DDB, AC, B, C, ABBA]
7     [C, CABBBADCD, DBCC, ACD]
8       [CC, A, BCAAAACBBA, BD]
9     [AC, A, ADBBD, BDCCDDABD]

快速获取小数据

%timeit df.assign(col1=np.core.defchararray.split(df.col1.values.astype(str), ','))
1000 loops, best of 3: 204 µs per loop

%timeit df.assign(col1=df['col1'].str.split(','))
1000 loops, best of 3: 327 µs per loop

%timeit df.assign(col1=[x.split(',') for x in df['col1'].values.tolist()])
1000 loops, best of 3: 210 µs per loop

对于大型数据而言不是那么快

np.random.seed([3,1415])
k = 10000
df = pd.DataFrame(
    np.random.choice(list('ABCD,'), (k, 100))
).sum(1).str.strip(',').str.replace(',+', ',').to_frame('col1')

%timeit df.assign(col1=np.core.defchararray.split(df.col1.values.astype(str), ','))
10 loops, best of 3: 19.6 ms per loop

%timeit df.assign(col1=df['col1'].str.split(','))
100 loops, best of 3: 13.5 ms per loop

%timeit df.assign(col1=[x.split(',') for x in df['col1'].values.tolist()])
100 loops, best of 3: 11.5 ms per loop