按字符串值排序数据帧

时间:2017-04-05 14:22:55

标签: python pandas dataframe

我的数据框如下所示:

Name  Net Worth
A     100M
B     200M
C     5M
D     40M
E     10B
F     2B

我想按Net Worth列中的值对其进行排序,对这些值进行排序的最佳方法是什么? M表示百万,B表示十亿,因此10B将是最高值。

1 个答案:

答案 0 :(得分:2)

您可以使用replace,创建新的已排序Series,然后reindex原创:

d = {'M': '0'*6, 'B': '0'*9}
s = df['Net Worth'].replace(d, regex=True).astype(float).sort_values(ascending=False)
print (df.reindex(s.index))
  Name Net Worth
4    E       10B
5    F        2B
1    B      200M
0    A      100M
3    D       40M
2    C        5M

更一般的解决方案,如果数据中有一些floats

print (df)
  Name Net Worth
0    A         1
1    B      200M
2    C        5M
3    D       40M
4    E      1.0B
5    F        2B

#dict for multiple
d = {'M': 10**6, 'B': 10**9}
#all keys of dict separated by | (or)
k = '|'.join(d.keys())

#replace by dict
a = df['Net Worth'].replace(d, regex=True).astype(float)
#remove M,B
b = df['Net Worth'].replace([k], '', regex=True).astype(float)
#multiple together, sorts
s = a.mul(b).sort_values(ascending=False)
#reindex - get sorted original
print (df.reindex(s.index))
  Name Net Worth
5    F        2B
4    E      1.0B
1    B      200M
3    D       40M
2    C        5M
0    A         1

另一个与extract类似的解决方案:

#dict for replace
_prefix = {'k': 1e3,    # kilo
           'M': 1e6,    # mega
           'B': 1e9,    # giga
}
#all keys of dict separated by | (or)
k = '|'.join(_prefix.keys())
#extract values to new df
df1 = df['Net Worth'].str.extract('(?P<a>[0-9.]*)(?P<b>' + k +')*', expand=True)
#convert numeric column to float
df1.a = df1.a.astype(float)
#map values by dictionary, replace NaN (no prefix) to 1
df1.b = df1.b.map(_prefix).fillna(1)
#multiple columns together
s = df1.a.mul(df1.b).sort_values(ascending=False)
print (s)
#sorting by reindexing
print (df.reindex(s.index))
  Name Net Worth
5    F        2B
4    E      1.0B
1    B      200M
3    D       40M
2    C        5M
0    A         1