2016-08-30 84 views
1

我有一个数据框;如何拆分“数字”以分隔大熊猫的列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

一种选择是使用extractall()方法与正则表达式(\d{2})(\d{2})(\d{2})其中每隔两个数字为列捕捉。 ?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