python - 将坐标打印到带有数据的 csv 文件
问题描述
我需要将相关数据的坐标提取到 .csv 文件中。
我有一个 4x4 矩阵,写成一个列表(network1)以及每个索引(q_val)的相应值。我的目标是确定 network1 中出现 1 的坐标,并将这些坐标与相应的 q_val 一起导出到 .csv 文件。
请看下面的当前代码:
network1 = [0,1,0,0,0,0,1,0,0,0,1,1,0,0,1,1]
q_val = [50,100,150,200,250,300,350,400,450,500,550,600,650,700,750,800]
data = np.array(network1)
shape = (4,4)
network2 = data.reshape(shape)
print(network2)
coordinates = np.where(network2 == 1)
print(coordinates)
listOfCoordinates= list(zip(coordinates[0], coordinates[1]))
for coords in listOfCoordinates:
print(coords)
这个过程的我的 Python 输出看起来是正确的,如下所示:
[[0 1 0 0]
[0 0 1 0]
[0 0 1 1]
[0 0 1 1]]
(array([0, 1, 2, 2, 3, 3], dtype=int64), array([1, 2, 2, 3, 2, 3], dtype=int64))
(0, 1)
(1, 2)
(2, 2)
(2, 3)
(3, 2)
(3, 3)
如果能获得一些帮助来完成以下附加步骤,那就太好了:
- 将索引移动 +1 [即结果应为 (1,2), (2,3), (3,3), (3,4), (4,3), (4,4)]。
- 将这些打印到不带括号和逗号的 .csv 文件中,仅由空格分隔。这应该看起来像下面的照片。
- 理想情况下,我还希望它在标题中打印 q_val 和 ; 低于结果。
我非常感谢任何帮助 - 我相信还有更有效的方法可以完成这个过程,所以我非常乐意接受任何建议!
解决方案
这应该满足您的要求:
import numpy as np
import pandas as pd
network1 = [0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1]
q_val = [50, 100, 150, 200, 250, 300, 350, 400, 450, 500, 550, 600, 650, 700, 750, 800]
network1_matrix = np.array(network1).reshape(4, 4)
q_val_matrix = np.array(q_val).reshape(4, 4)
coordinates = np.transpose(np.where(network1_matrix == 1))
filtered_values = [q_val_matrix[tuple(coordinate)] for coordinate in coordinates]
# Create the DataFrame and add 1 to each index
result_df = pd.DataFrame({'1': coordinates[:, 0] + 1, '2': coordinates[:, 1] + 1, '3': filtered_values})
# Add ';' in the end of the DataFrame
result_df = result_df.append({'1': ';', '2': '', '3': ''}, ignore_index=True)
# Add 'q_val' as header
result_df.columns = ['q_val', '', '']
# Export the DataFrame as csv file
result_df.to_csv('result.csv', sep=' ', index=False)
推荐阅读
- vba - VBA:查找日期
- swift - 调用 'subscribe(onNext:onError:onCompleted:onDisposed:)' 的结果未使用
- javascript - .click() 回调函数解释
- html - Angular 8 中的 HTML 绑定
- vagrant - “不支持的加密类型”的可能原因 - vagrant 中的错误
- c# - Serilog - 如何在滚动文件名中自定义日期?
- c# - 如何设置阴影属性的默认值
- excel - 在 Excel 中使用 MEDIAN IF 函数作为索引?
- visual-studio-2017 - 重新定位到网络标准 2.0 后,无法构建解决方案和打开项目属性
- r - R.utils::withTimeout,在 Linux 上的工作方式与在 Windows 上不同