如何按行对数据框进行排序?

时间:2016-08-14 11:24:29

标签: python pandas dataframe

我有一个数据框:

import pandas as pd

df = pd.DataFrame(data={'x':[7,1,9], 'y':[4,5,6],'z':[1,8,3]}, index=['a', 'b', 'c'])

它显示:

enter image description here

如何按行排序此数据框[' a']: 对数据帧进行排序后,可能是:

enter image description here

4 个答案:

答案 0 :(得分:5)

var q = from internalMaterialIssueVocherDetail in _ctx.InternalMaterialIssueVoucherDetails
        where internalMaterialIssueVocherDetail.InternalMaterialIssueVoucherId == Id
        join line in _ctx.Lines on internalMaterialIssueVocherDetail.LineId equals line.Id
        join joint in _ctx.Joints on internalMaterialIssueVocherDetail.JointId equals joint.Id
        join sheet in _ctx.Sheets on joint.SheetId equals sheet.Id
        join material in _ctx.Materials on line.Id equals material.LineId 
        //join materialDescription in _ctx.MaterialDescriptions on material.MaterialDescriptionId equals materialDescription.Id
        join testPackageJoint in _ctx.TestPackageJoints on joint.Id equals testPackageJoint.JointId
        join testPackage in _ctx.TestPackages on testPackageJoint.TestPackageId equals testPackage.Id
        select new ViewIMIV()
                   {
                      // ItemCode = materialDescription.ItemCode,
                      // MaterialDescription = materialDescription.Description,
                      SheetNumber = sheet.SheetNumber,
                      LineNumber = line.LineNumber,
                      TestPackageNumber = testPackage.PackageNumber,
                      QuantityDeliverToMember = internalMaterialIssueVocherDetail.QuantityDeliverToMember.ToString(),
                      //Size = materialDescription.Size1
                   };

In [7]: df.iloc[:, np.argsort(df.loc['a'])] Out[7]: z y x a 1 4 7 b 8 5 1 c 3 6 9 返回用于对np.argsorta行进行排序的索引:

df.loc['a']

获得这些索引后,您可以使用它们对In [6]: np.argsort(df.loc['a']) Out[6]: x 2 y 1 z 0 Name: a, dtype: int64 的列进行重新排序(使用df)。

答案 1 :(得分:3)

您可以使用sed -i -e 's/\(^var1=\).*/\1Newvalue/' $INPUT 方法:

reindex_axis

答案 2 :(得分:2)

您可以在致电sort时使用axis=1

df.sort(axis=1, ascending=False)   

>>       z  y  x
      a  1  4  7
      b  8  5  1
      c  3  6  9

请注意,sort默认不在位,因此要么重新分配其返回值,要么使用inplace=True

答案 3 :(得分:1)

在v0.19中,您可以按行排序:

pd.__version__
Out: '0.19.0rc1'

df.sort_values(by='a', axis=1)
Out: 
   z  y  x
a  1  4  7
b  8  5  1
c  3  6  9