我是 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']})
首先,我喜欢对'year_week'
列进行升序排列(2015_1, 2016_9, '2016_9', 2016_10, 2016_11, 2016_3, 2016_10, 2016_10)
然后为每个唯一的 'year_week'
字符串生成一个数值。
最佳答案
您可以先转换to_datetime
列 year_week
,然后按 sort_values
排序最后一次使用factorize
:
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
关于python - 对 Pandas 中包含字符串的列进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39015931/