python – zip,sorted和pandas

我有一个pandas数据框,其列值如下:

names = wine_df.columns
names
Index([u'fixed acidity', u'volatile acidity', u'citric acid', u'residual sugar', u'chlorides', u'free sulfur dioxide', u'total sulfur dioxide', u'density', u'pH', u'sulphates', u'alcohol'], dtype='object')

我有一个名为imp的numpy数组,其中包含以下值:

array([ 0.07640909,  0.11346059,  0.09160943,  0.06674312,  0.07203855,
        0.06306923,  0.08272078,  0.0839144 ,  0.05996705,  0.11833288,
        0.17173489])

我正在研究一个项目,我遇到了如下所示的代码:

zip(*sorted(zip(imp, names)))

我无法理解为什么他们使用*在zip函数内排序?还为什么他们两次使用拉链功能?

最佳答案 看看他在做什么的最好方法是用一个简单的例子:

In [11]: a = np.array([2, 1, 3])

In [12]: a = np.array([2, 1, 2, 3])

In [13]: b = np.array(['b', 'b', 'a', 'c'])

In [14]: sorted(zip(a, b))
Out[14]: [(1, 'b'), (2, 'a'), (2, 'b'), (3, 'c')]

In [15]: zip(*sorted(zip(a, b)))
Out[15]: [(1, 2, 2, 3), ('b', 'a', 'b', 'c')]

它根据第一个中的值对两个列表/数组进行排序(后面是第二个中的值).

一个更“笨拙”的方法是使用argsort(对于更大的数组,性能会更高):

In [21]: s = np.argsort(a)

In [22]: a[s], b[s]
Out[22]:
(array([1, 2, 2, 3]), array(['b', 'b', 'a', 'c'],
       dtype='|S1'))

注意:给出略有不同的结果,因为它不处理a中的绘制.

点赞