2016-08-30 5 views
1

데이터 프레임이 있습니다.'number'를 팬더의 열을 분리하는 방법 DataFrame

df=pd.DataFrame({'col1':[100000,100001,100002,100003,100004]}) 

    col1  
0 100000  
1 100001 
2 100002 
3 100003 
4 100004 

나는 아래 결과를 얻을 수 있었으면 좋겠다.

col1 col2 col3 
0 10  00  00 
1 10  00  01 
2 10  00  02 
3 10  00  03 
4 10  00  04 

각 행은 분할 된 수를 표시합니다. 숫자가 문자열로 변환되어야한다고 생각하지만 다음 단계는 잘 모른다. ... 숫자를 분리하여 열을 구분하는 방법을 묻고 싶다.

답변

4
# make string version of original column, call it 'col' 
df['col'] = df['col1'].astype(str) 

# make the new columns using string indexing 
df['col1'] = df['col'].str[0:2] 
df['col2'] = df['col'].str[2:4] 
df['col3'] = df['col'].str[4:6] 

# get rid of the extra variable (if you want) 
df.drop('col', axis=1, inplace=True) 
+0

빠른 응답을 가져 주셔서 감사합니다. 이 방법은 매우 간단합니다! 나는 많이 배웠다! – Heisenberg

2

하나의 옵션은 열 등의 다른 모든 두 자리 숫자를 캡처 정규식 (\d{2})(\d{2})(\d{2})extractall() 방법을 사용하는 것입니다. ?P<col1>은 열 이름으로 변환 될 캡처 된 그룹의 이름입니다.

df.col1.astype(str).str.extractall("(?P<col1>\d{2})(?P<col2>\d{2})(?P<col3>\d{2})").reset_index(drop=True) 

# col1 col2 col3 
# 0 10 00 00 
# 1 10 00 01 
# 2 10 00 02 
# 3 10 00 03 
# 4 10 00 04 
관련 문제