【问题标题】:np.where() solution explanation [closed]np.where() 解决方案说明 [关闭]
【发布时间】:2019-05-23 12:11:04
【问题描述】:

我正在这里练习: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] )。

【问题讨论】:

  • 明白。你有什么问题?
  • 我的最后一句话。我不明白括号中的零的功能和位置。我不明白他们在做什么,他们在函数中代表什么。
  • 这不是问题。那是一个声明。你有什么不明白的?可回答问题的一些示例:“[0] 对列表有什么作用?”、“为什么我必须取 np.where 的第 0 个元素?”、“np.where 有什么作用?”、“tolist 有什么作用? () 做什么?”等

标签: python python-3.x numpy


【解决方案1】:

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。

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

【讨论】:

  • 您写道:“最好使用找到的索引来扩展 list1,因为当一个元素多次出现时,此代码将失败。”您能否指出我的代码示例。我希望看到一个元素出现多次时不会中断的代码。另外,我尝试了:[np.where(i == ser1)[0][0] for i in ser2],按照您的建议删除不需要的 to_list(),它工作得很好。
  • 编辑答案以包含扩展
猜你喜欢
  • 2020-03-02
  • 2015-03-18
  • 1970-01-01
  • 2020-10-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-15
相关资源
最近更新 更多