2016-08-18 10 views
2

私はPandasを初めて使っていて、文字列を含む列をソートし、その文字列を一意に識別する数値を生成したいと考えています。私は昇順(2015_1, 2016_9, '2016_9', 2016_10, 2016_11, 2016_3, 2016_10, 2016_10)にアレンジし、各ユニーク'year_week'文字列の数値を生成する'year_week'列をソートしたいとPandasの文字列を含む列をソート

df = pd.DataFrame({'key': range(8), 'year_week': ['2015_10', '2015_1', '2015_11', '2016_9', '2016_10','2016_3', '2016_9', '2016_10']}) 

まず:私のデータフレームは、次のようになります。

答えて

3

あなたはまずsort_valuesと最後の使用factorizeことによってそれを並べ替え、to_datetimeyear_weekを変換することができます:

df = pd.DataFrame({'key': range(8), 'year_week': ['2015_10', '2015_1', '2015_11', '2016_9', '2016_10','2016_3', '2016_9', '2016_10']}) 

#http://stackoverflow.com/a/17087427/2901002 
df['date'] = pd.to_datetime(df.year_week + '-0', format='%Y_%W-%w') 
#sort by column date 
df.sort_values('date', inplace=True) 
#create numerical values 
df['num'] = pd.factorize(df.year_week)[0] 
print (df) 
    key year_week  date num 
1 1 2015_1 2015-01-11 0 
0 0 2015_10 2015-03-15 1 
2 2 2015_11 2015-03-22 2 
5 5 2016_3 2016-01-24 3 
3 3 2016_9 2016-03-06 4 
6 6 2016_9 2016-03-06 4 
4 4 2016_10 2016-03-13 5 
7 7 2016_10 2016-03-13 5 
+0

はどうもありがとうございました!それは私の問題を解決した – Nadne

関連する問題