np.where()解决方案解释



我正在这里进行练习:https://www.machinelearningplus.com/python/101-pandas-eccers-cercises-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](。

np。在哪里输出元组(numpy.where(条件(不是数组,而是数组元组:为什么?(,因此您必须索引(因此,第一个[0](因此,输出是元素的数量阵列。在这种情况下,只有一个,因此第二个[0]有效。尽管

是完全冗余的tolist((

最好用找到的索引扩展List1,因为当元素发生不止一次时,此代码会失败:

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

不是最好的代码IMO。

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

相关内容

最新更新