0

我正在尝试使用 df.sort_index 按列对数据框进行排序。第二个这样的字符串列是由文本中的数字组成的。手术后我有:

15 rs1820451 32681212 0.441 0.493 0.5358 98.9 29 0 0.441 T:A 
14 rs1820450 32680556 0.441 0.493 0.5358 98.9 29 0 0.441 G:C 
38 rs1820447 32693541 0.421 0.332 0.0915 94.4 26 0 0.211 G:A 
37 rs1820446 32693440 0.483 0.499 0.9633 100.0 30 0 0.475 G:T 
7 rs1808502 32660555 0.517 0.46 0.543 100.0 30 0 0.358 C:G 
24 rs17817908 32687035 0.407 0.362 0.6159 98.9 29 0 0.237 C:T 
22 rs17817896 32686160 0.407 0.362 0.6159 98.9 29 0 0.237 T:A 
66 rs17236946 32717247 0.492 0.453 0.7762 98.9 29 0 0.347 T:C

这不是我想要的。最后三行应该在开头。是否有任何其他数据框方法或克服此问题?

4

3 回答 3

1

如果要对一列或多列进行排序,则需要使用 df.sort(),df.sort_index() 仅对索引进行排序。

于 2012-09-28T14:18:27.567 回答
0

这根本没有错误检查或优化,但这是你想要的:

def sort_on(lines, col_idx):
  return sorted(lines, key=lambda l: float(l.split()[col_idx]))

lines = """\
15 rs1820451 32681212 0.441 0.493 0.5358 98.9 29 0 0.441 T:A 
14 rs1820450 32680556 0.441 0.493 0.5358 98.9 29 0 0.441 G:C 
38 rs1820447 32693541 0.421 0.332 0.0915 94.4 26 0 0.211 G:A 
37 rs1820446 32693440 0.483 0.499 0.9633 100.0 30 0 0.475 G:T 
7 rs1808502 32660555 0.517 0.46 0.543 100.0 30 0 0.358 C:G 
24 rs17817908 32687035 0.407 0.362 0.6159 98.9 29 0 0.237 C:T 
22 rs17817896 32686160 0.407 0.362 0.6159 98.9 29 0 0.237 T:A 
66 rs17236946 32717247 0.492 0.453 0.7762 98.9 29 0 0.347 T:C
""".splitlines()

sorted_lines = sort_on(lines, 3)
print "\n".join(sorted_lines)
于 2012-09-28T14:16:00.290 回答
0

对于期货参考,这里有一个可能的解决方案。

    cond = ((df['L1'] != rscode) & (df['L2'] != rscode))
    outname = inf + '_test'
    df['L3'] = df['L1'].map(lambda x: int(str(x)[2:]))        
    outdata = df.drop(df[cond].index.values).sort(columns='L3', ascending=False, axis=0)
    # export outdata using Datadrame.to_csv with the original df cols

欢迎改进。最好的,

于 2012-09-28T22:41:05.493 回答