2016-08-30 8 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

1つのオプションは、カラムとして、他のすべての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 
関連する問題