python - 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.]])
我想编写一个按行工作并找到相似之处的函数。
函数的输入应该是可变的,例如,预期的输入可以是192或185,185。
基于该输入,算法应该搜索(for
我猜是一个循环)具有第一列的条目(对于输入192,这将是第一列,对于输入185,185,这将是前两列)和将匹配的行返回给我。
例如,对于输入185,185,应返回最后两行。
我应该为其编写代码的最佳数据类型是什么?
到目前为止,我知道字典、列表和数据帧。我还种子 DataFrames 集成字典。我倾向于使用 pandas 数据框,但我不确定它们如何处理可变数量的输入。
解决方案
这取决于您的要求和知识。对于一个很小的数据集,你知道的方式将是编写给出解决方案的代码的最快方式。如果你想用 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
推荐阅读
- google-cloud-platform - 有谁知道云运行是否支持 http/2 流而不支持 http1.1 流?
- python - 为什么 Python 只允许我使用一次打开的文件?
- python - Mongodb 4.2 使用聚合管道更新更快的方法来仅更新数组中的一个元素?
- javascript - 用新的道具值渲染组件的变化?
- jestjs - spyOn @react-native-firebase/分析方法
- selenium - 如何在 Heroku 上使用 Capybara/Firefox 和代理?我得到“代理服务器拒绝连接”
- javascript - 功能未按顺序运行
- c++ - OpenGL:Lambert 着色导入的 OBJ 会导致伪影和奇怪的剔除
- cuda - __cudaUnregisterFatBinary() (NVCC 10.2) 与 __cudaUnregisterFatBinary() (NVCC 10.0) 的 Cuda 应用程序段错误
- inheritance - Rust:如何为特征的某些“子类”定义常见行为?