np.where()解决方案说明

时间:2019-05-23 12:11:05

标签: python python-3.x numpy

我正在这里进行练习:https://www.machinelearningplus.com/python/101-pandas-exercises-python/

问题16有一个我无法理解的使用np.where()的解决方案(#1)。

import pandas as pd
import numpy as np


print('pandas: {}'.format(pd.__version__))
print('NumPy: {}'.format(np.__version__))
print('-----')

ser1 = pd.Series([10, 9, 6, 5, 3, 1, 12, 8, 13])
ser2 = pd.Series([1, 3, 10, 13])

# Get the positions of items of 'ser2' in 'ser1' as a list.

# Solution 1
list1 = [np.where(i == ser1)[0].tolist()[0] for i in ser2]
print(list1)
print()

# Solution 2
list2 = [pd.Index(ser1).get_loc(i) for i in ser2]
print(list2)

我在这里查找了np.where():

# https://stackoverflow.com/questions/34667282/numpy-where-detailed-step-by-step-explanation-examples
# https://thispointer.com/numpy-where-tutorial-examples-python/
# https://www.geeksforgeeks.org/numpy-where-in-python/

确切地说,我不了解两者的功能和位置 放在括号中的零([0])。

1 个答案:

答案 0 :(得分:0)

np.where输出一个元组(output of numpy.where(condition) is not an array, but a tuple of arrays: why?),因此您必须对其进行索引(因此第一个[0]),然后输出是一个numpy元素数组。在这种情况下只有一个,因此第二个[0]有效。尽管tolist()完全是多余的

最好用找到的索引扩展list1,因为当一个元素出现多次时,此代码将失败:

list1 = []
[list1.extend(np.where(i == ser1)[0]) for i in ser2]
print(list1)
print()

不是最好的代码imo。

提示,只要自己检查一下东西的输出,就可以弄清楚了。只需运行np.where(i==ser1),您就会看到它返回一个元组,您需要对其进行索引。等

相关问题