簡體   English   中英

如何在python中拆分DataFrame列

[英]How to split a DataFrame column in python

我有要拆分的DataFrame列。 例如:

     0     1     2
0    a     b     c-d-e
1    f     g     h-i-j
2    k     l     m-n-o

該信息存儲在DataFrame中。 如何將數據框更改為此?

     0     1     2     3     4
0    a     b     c     d     e
1    f     g     h     i     j
2    k     l     m     n     o

謝謝

您正在尋找Series.str.split

>>> print df[2].str.split('-', expand=True)
   0  1  2
0  c  d  e
1  h  i  j
2  m  n  o

>>> pd.concat((df[[0, 1]], df[2].str.split('-', expand=True)), axis=1, ignore_index=True)
   0  1  2  3  4
0  a  b  c  d  e
1  f  g  h  i  j
2  k  l  m  n  o

如果您使用的熊貓版本早於0.16.1,則要使用return_type='frame'而不是expand=True

您可以使用DataFrame構造函數:

print df

#   0  1      2
#0  a  b  c-d-e
#1  f  g  h-i-j
#2  k  l  m-n-o

df[[2, 3, 4]] = pd.DataFrame([ x.split('-') for x in df[2].tolist() ])
print df

#   0  1  2  3  4
#0  a  b  c  d  e
#1  f  g  h  i  j
#2  k  l  m  n  o

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM