2015-01-31 54 views
1

我想根據分隔符":"將列拆分爲3,並且我能夠使用下面的代碼執行 。但是現在想要將默認的1,2,3,4分割列的名稱改爲 。請告訴我如何做到這一點。拆分列並使用熊貓命名它們

from pandas import * 
df = DataFrame(
    {'CustomerName' : ["Paul", "John"], 'Seatblocks' : ["2:218:10:4,6","2:218:10:4,6"]}); 
df 

df.join(df.Seatblocks.apply(lambda x: Series(x.split(':')))) 

回答

1

列被重命名爲A,B,C,D

from pandas import * 
df = DataFrame(
    {'CustomerName' : ["Paul", "John"], 'Seatblocks' : ["2:218:10:4,6","2:218:10:4,6"]}); 
df = df.join(df.Seatblocks.apply(lambda x: Series(x.split(':')))) 
df.rename(columns={0: 'A', 1: 'B', 2: 'C', 3: 'D'}, inplace=True) 
df 
1

只是rename他們:

df.rename(columns={0:'col_1', 1:'col_2', 2:'col_3', 3:'col_4'},inplace=True) 

一個比較模糊的方法是形成新名稱的工會到列中的前2個元素並直接指定:

In [14]: 

df.columns = df.columns[:2] | pd.Index(['col_1', 'col_2', 'col_3', 'col_4']) 
df 
Out[14]: 
    CustomerName Seatblocks col_1 col_2 col_3 col_4 
0   Paul 2:218:10:4,6  2 218 10 4,6 
1   John 2:218:10:4,6  2 218 10 4,6 
2

人們已經給出了rename的方法,但是如果你避免把所有東西塞進一行,我覺得這些事情更容易。一旦你有一個框,你可以簡單地分配給.columns

>>> sb = df.Seatblocks.str.split(":").apply(pd.Series) 
>>> sb.columns = ["a", "Three Digit", "??", "coord"] 
>>> pd.concat([df, sb], axis=1) 
    CustomerName Seatblocks a Three Digit ?? coord 
0   Paul 2:218:10:4,6 2   218 10 4,6 
1   John 2:218:10:4,6 2   218 10 4,6 

第一行是一個簡單的版本的(df.Seatblocks.apply(lambda x: Series(x.split(':'))))的這需要向量化字符串操作訪問.strdocs)的優勢。

0

可以修改df.column來獲得新的列名

In [1]: from pandas import * 

In [2]: df = DataFrame(
    ...:  {'CustomerName' : ["Paul", "John"], 'Seatblocks' : ["2:218:10:4,6","2:218:10:4,6"]}); 

In [3]: df2 = df.join(df.Seatblocks.apply(lambda x: Series(x.split(':')))) 

In [4]: names = ['foo', 'bar', 'baz', 'booz'] 

In [5]: df2.columns = [x if str(x).isalpha() else names.pop() for x in df2.columns] 

In [6]: df2.columns            
Out[6]: Index([u'CustomerName', u'Seatblocks', u'booz', u'baz', u'bar', u'foo'], dtype='object') 

In [7]: