【问题标题】:Pandas: sorting numbers within text by columnPandas:按列对文本中的数字进行排序
【发布时间】:2012-09-20 10:23:18
【问题描述】:

我正在尝试使用 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

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

【问题讨论】:

    标签: python sorting dataframe pandas


    【解决方案1】:

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

    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)
    

    【讨论】:

    • 嗨,spiralx,感谢您的帮助。它有效,但它不是一个可行的解决方案。这样 a 将不得不将我的整个数据框传递给一个字符串。
    • 除了子类化DataFrame 和重载DataFrame.iteritems,或者使用DataFrame.apply 来获取一个提取了数值的新df 之外,我看不到任何明显的方法。那,或者生成具有不同列结构的对象,可能是最简单的。
    【解决方案2】:

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

    【讨论】:

    • outdata.sort(columns='Name', ascending=True, axis=0),除非我做错了什么,否则它仍然不起作用。
    【解决方案3】:

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

        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
    

    欢迎改进。 最好的,

    【讨论】:

      猜你喜欢
      • 2017-04-12
      • 1970-01-01
      • 2020-11-19
      • 2014-08-31
      • 2020-11-21
      • 2017-04-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多