首页 > 解决方案 > Python,用于查找和提取相似性的结构。列表。字典还是数据框?

问题描述

我有一些当前存储在数组中的测量值:

    myMatrix[:5,:5]
    Out[11]: 
    array([[192., 192.,   0.,   0.,   0.],
    [185., 171.,   0.,   0.,   0.],
    [ 17.,   1.,  16.,  17.,   1.],
    [185., 185.,   0.,   0.,   0.],
    [185., 185.,   0.,   0.,   0.]])

我想编写一个按行工作并找到相似之处的函数。

函数的输入应该是可变的,例如,预期的输入可以是192185,185

基于该输入,算法应该搜索(for我猜是一个循环)具有第一列的条目(对于输入192,这将是第一列,对于输入185,185,这将是前两列)和将匹配的行返回给我。

例如,对于输入185,185,应返回最后两行。

我应该为其编写代码的最佳数据类型是什么?

到目前为止,我知道字典、列表和数据帧。我还种子 DataFrames 集成字典。我倾向于使用 pandas 数据框,但我不确定它们如何处理可变数量的输入。

标签: pythonpandaslisttypes

解决方案


这取决于您的要求和知识。对于一个很小的数据集,你知道的方式将是编写给出解决方案的代码的最快方式。如果你想用 pandas 做实验,或者如果数据集很大,pandas 肯定是一个不错的方法,因为它可以直接使用 numpy 数组。

在这里你可以使用:

def find_start(mat, *val):
    # convert the argument list to a ndarray of right type
    s = np.array(val, dtype = mat.dtype)
    # compare the start of each line with that ndarray (assuming s is shorter than the line)
    return (df.iloc(1)[0:len(s)] == s).agg(all, axis=1)

然后使用您的示例数据:

>>> print(find_start(myMatrix, 192))
0     True
1    False
2    False
3    False
4    False
dtype: bool
>>> print(find_start(myMatrix, 185, 185.))
0    False
1    False
2    False
3     True
4     True
dtype: bool

推荐阅读