Python,用于查找和提取相似性的结构。列表。字典还是数据帧?

2024-04-25 01:11:49 发布

您现在位置: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.]])

我想写一个按行运行并找到相似之处的函数。你知道吗

函数的输入应该是可变的,例如,预期的输入可以是192185185。你知道吗

基于该输入,算法应该搜索(我猜是for循环)具有第一列的条目(对于输入192,它将是第一列,对于输入185185,它将是前两列),并返回匹配所在的行。你知道吗

例如,对于输入185185,应该返回最后两行。你知道吗

我应该为哪种数据类型编写代码?你知道吗

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


Tags: 数据函数代码算法pandas列表for数量
2条回答

在这种情况下使用熊猫和裸体。你知道吗

import pandas as pd
import numpy as np

df = pd.DataFrame(np.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.]]), 
columns=['a', 'b', 'c', 'd', 'e'])

这取决于你的要求和知识。对于一个很小的数据集,您所知道的编写代码给出解决方案的方式将是最快的。如果你想用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

相关问题 更多 >