2015-01-31 3 views
1

열을 구분 기호 ":"을 기준으로 3으로 분할하고 아래 코드를 사용하여 할 수 있습니다. 그러나 이제 split 열의 이름을 기본값 인 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) 

열의 처음 두 요소에 직접 할당 :

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 

첫 번째 줄은 단순히 벡터화 된 문자열 연산 접근 .str (docs)을 활용하여 (df.Seatblocks.apply(lambda x: Series(x.split(':'))))의 버전입니다.

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]: 
관련 문제