【问题标题】:Searching index position in python在python中搜索索引位置
【发布时间】:2022-01-07 13:54:00
【问题描述】:
cols = [2,4,6,8,10,12,14,16,18] # selected the columns i want to work with
df = pd.read_csv('mywork.csv')
df1 = df.iloc[:, cols]
b= np.array(df1)
b
outcome
b = [['WV5 6NY' 'RE4 9VU' 'BU4 N90' 'TU3 5RE' 'NE5 4F']
   ['SA8 7TA' 'BA31 0PO' 'DE3 2FP' 'LR98 4TS' 0]
   ['MN0 4NU' 'RF5 5FG' 'WA3 0MN' 'EA15 8RE' 'BE1 4RE']
   ['SB7 0ET' 'SA7 0SB' 'BT7 6NS' 'TA9 0LP' 'BA3 1OE']]

a = np.concatenate(b) #concatenated to get a single array, this worked well

a = np.array([x for x in a if x != 'nan'])
a = a[np.where(a != '0')] #removed the nan
print(np.sort(a)) # to sort alphabetically

#Sorted array
['BA3 1OE' 'BA31 0PO' 'BE1 4RE' 'BT7 6NS' 'BU4 N90'
'DE3 2FP' 'EA15 8RE' 'LR98 4TS' 'MN0 4NU', 'NE5 4F' 'RE4 9VU'
'RF5 5FG' 'SA7 0SB' 'SA8 7TA' 'SB7 0ET' 'TA9 0LP' 'TU3 5RE'
'WA3 0MN' 'WV5 6NY']

#Find the index position of all elements of b in a(sorted array)
def findall_index(b, a )
    result = []
    for i in range(len(a)):
       for j in range(len(a[i])):
           if b[i][j] == a:
               result.append((i, j))
    return result
print(findall_index(0,result))

我对python还是很陌生,我尝试在上面的a中找到b的所有元素的索引位置。下面的代码块似乎没有给我任何结果。请有人帮助我。

提前谢谢你。

【问题讨论】:

  • 你调试过这个吗? PyCharm 是一个免费的 Python IDE,带有一个很棒的内置调试器,here's 如何使用它。您可以逐行执行程序,并在每一步检查每个变量的内容。调试对于知道如何去做非常重要,因为随机的陌生人不会总是愿意为你做。事实上,我会说这是第 1 天,对于任何程序员来说都是必不可少的工具。
  • stackoverflow.com/questions/6422700/… 可能会有所帮助...

标签: python matrix position mapping z-index


【解决方案1】:

解决此问题的一种方法是将 b 中的元素索引与实际元素压缩(创建对),然后仅根据元素对这个新数组进行排序。现在您有了从原始数组的索引到新排序数组的映射。然后,您可以遍历已排序的对以将当前索引映射到原始索引。

我强烈建议您自己编写代码,因为它会帮助您学习!

【讨论】:

  • 我一直收到这个错误 :1: FutureWarning: elementwise comparison failed;而是返回标量,但将来会执行元素比较
猜你喜欢
  • 1970-01-01
  • 2014-07-26
  • 1970-01-01
  • 1970-01-01
  • 2011-11-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-09
相关资源
最近更新 更多