我有一个 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 函数中使用 *sorted?还有为什么他们两次使用 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')]
它根据第一个中的值对两个列表/数组进行排序(然后是第二个中的值)。
一个更“numpy”的方法是使用 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 中的平局。
关于python - zip、排序和 Pandas ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28341387/