无法正确排序泰坦尼克号数据集的Cabin值

时间:2016-10-25 20:56:02

标签: sorting pandas

所以我有一系列Cabin值;左边是索引,右边列是Cabin值。使用sort_values方法后,我只能对值进行部分排序。

x =  Cabin_Fare=Cabin_Fare.sort_values(['Cabin' ]) 

210      A31
186      A32
446      A34
1185     A34
1266     A34
807      A36
97       A 
24       A6 
175      A7 
1058     B10
738     B101
816     B102
1107     B11
330      B18
524      B18
171      B19
691      B20
660      D48
682      D49
626      D50
22       D56
783      D6 
276      D7 
628      D9 
430      E10
718      E101
304      E101
124      E101
461      E12
752      E121
1234     NaN
1252     NaN
1257     NaN
73       NaN
121      NaN

我遇到的问题是尽管能够对机舱信件进行分类,但我很难按照客舱信件上的数字进行排序。 所以我想要的输出是

97       A 
24       A6 
175      A7 
210      A31
186      A32
446      A34
1185     A34
1266     A34
807      A36
1058     B10
1107     B11
330      B18
524      B18
171      B19
691      B20
738     B101
816     B102
........

1234     NaN
1252     NaN
1257     NaN
73       NaN
121      NaN

我并不是特别关注NaN值,但我希望它们在系列的最后。单独的Cabin值,例如单独的“A”可以在必要时添加“0”,但我希望没有数字的字母附加到它们上面,成为列表中的第一个。

我得到了一些想法,但事实证明这个代码(下面),与字母的顺序混淆。我想保留字母顺序。

 x.reindex(x[x.notnull()].str[1:].replace('', 0).astype(int).sort_values().index)

感谢。

2 个答案:

答案 0 :(得分:3)

# setup regex for str.extract
# ?P<letter> tells pandas to make that a column with name 'letter'
regex = '(?P<letter>\D+)(?P<digit>\d*)'
# easy access to column names I'm making in extract step
cols = ['letter', 'digit']

# run extract.  will pull out letter and digit
split_df = df.Cabin.str.extract(regex, expand=True)
# make sure digit column is numeric and fill with 0
split_df['digit'] = pd.to_numeric(split_df['digit'], 'coerce').fillna(0)
# sort by cols gets us the right sort
split_df.sort_values(cols, inplace=True)
# use sorted split_df.index for a slice
df = df.ix[split_df.index]
df.head(20)

enter image description here

答案 1 :(得分:2)

您可以轻松地将其拆分为字母和数字:

letter, numbers = cabin[0], cabin[1:]