python - 如何为熊猫数据框中的每一行创建坐标列表?
问题描述
我有一个数据框,其中包含帧序列中几个 2d 点的坐标。看起来像
frame point_1_x point_2_x point_3_x point_1_y point_2_y point_3_y
1 0 1 1 2 3 1
2 2 3 5 1 2 3
3 8 2 3 4 5 6
我想以类似数组的结构形式提取给定点索引的坐标。例如:
def extract_points(df, indices):
'''
Takes dataframe and indices of points
returns list of coordinates of points
'''
extract_points(example_dataset, [1,2])
output: np.array([[(0, 2), (2,1), (8, 4)], [(1,3), (3,2), (2,5)]])
我怎样才能使用numpy
和以pythonic方式做到这一点pandas
?
解决方案
重命名列,然后 groupby
df.columns = df.columns.str[:-2]
arr = df.stack().groupby(level=[1,0]).agg(tuple).values
array([(0, 2), (2, 1), (8, 4), (1, 3), (3, 2), (2, 5), (1, 1), (5, 3),
(3, 6)], dtype=object)
推荐阅读
- azure - Azure 函数存储文件不会随函数一起删除
- scala - 在 Scala 匹配表达式中利用案例类的类型约束
- javascript - 使用deck.gl根据滑块输入更改图层属性
- azure - Azure Pipelines (DevOps):自定义耗材统计/指标
- python-3.x - 有没有关于在 python 中使用 .dat(音频文件不是视频)文件的参考?
- java - 从具有 Spring 和 JPA 注释的两个表之间具有外键关系的 html 表单(使用 Thymeleaf)保存数据的问题
- machine-learning - feature_contribs 和特征重要性的区别
- powershell - 比较两个重复的文本文件并将明显的差异写入文本文件
- android - Viewflipper 固定在顶部,滚动时不隐藏
- powershell - 从“第二个”Powershell 进程获取返回码