【问题标题】:How to loop over 2D matrix with condition如何使用条件循环二维矩阵
【发布时间】:2017-01-25 11:41:12
【问题描述】:

我是 python 新手,想弄清楚如何遍历 2x2 矩阵。

我的起点是一个 *.csv 文件,其中包含大量数据(10 列,173828 行)。因为我只需要第一列(sigma_0 值)和第六列(日期),所以我做了一个矩阵叫做 sigma_JD,它只包含这两列:

    import csv
    import numpy as np
    with open("C:/Users/.../03971822.csv") as input_file:
       reader = csv.reader(input_file)

       array = []
       for row in reader:
       array.append(row)

    matrix = np.asmatrix(array)
    idx_IN_columns = [0, 5]
    sigma_JD = matrix[:, idx_IN_columns]
    print(sigma_JD)
    print("size sigma_JD: ", np.shape(sigma_JD))

    >>> print(sigma_JD)
    [['-12.42' '2451544.576']
     ['-12.92' '2451544.576']
     ['-12.45' '2451544.576']
     ..., 
     ['-11.66' '2454688.389']
     ['-12.61' '2454688.389']
     ['-11.72' '2454688.389']]
    >>> print("size sigma_JD: ", np.shape(sigma_JD))
    size sigma_JD:  (173828, 2)

现在我想遍历第二列 - 日期;它以特定方式显示,称为“朱利安日”,例如JD值是

            2451544,5 = 01/January/2000 0:00
            2451545,5 = 02/January/2000 0:00
            2451546,5 = 03/January/2000 0:00

2451544 表示日/月/年,小数位表示时间。

我想编写一个代码,其中考虑了所有 sigma_0 值,它们都在一天之内。因此,循环应该使用特定的值,而不是通过索引。

它应该从 2451544,5 开始,然后考虑当天所有的 sigma_0 值(并总结),然后转到第二天 2451544,5 并执行相同的操作....

我试过了。像这样,但它不起作用

    x = 2451544.5
    y = x + 1
    for i in sigma_JD[:, 1]:
        while x < y:
    print(sigma_JD[i, 1])
    break

然后我想创建自己的函数,但没有走那么远:

   def select(x):
   count = 2451544.5
   select = []  
   for i in range(0, len(x[:, 1])):   # loop over Julian Day
      if count < count + 1:
        row = []
        for j in range(0, len(x[:, 0])):   # loop over sigma_0 values
           # take all sigma_0 values and sum it up
        count += 1
   return select

如果有人能帮助我,那就太好了。我为此工作了好几天,真的让我很沮丧,我不知道如何完成这项工作。

非常感谢。

【问题讨论】:

标签: python loops matrix


【解决方案1】:

试一试(您可能需要下载jdcal package

import csv
import collections
from jdcal import jd2gcal

with open("test.csv") as input_file:
    reader = csv.reader(input_file)

    jd_sigma_map = collections.defaultdict(int)
    jd_sigma_count = collections.defaultdict(int)

    for row in reader:

        #convert to the normal date format
        year, month, dd, ms = jd2gcal(float(row[5]), 0)

        #use date as key
        date_key = '%s-%s-%s' % (year, month, dd)

        #Sum sigma values for same key (day)
        jd_sigma_map[date_key] += float(row[0])
        jd_sigma_count[date_key] += 1

测试文件 (test.csv):

-12.42, 0, 0, 0, 0, 2451544.576
-12.92, 0, 0, 0, 0, 2451544.576
-5.92,  0, 0, 0, 0, 2451545.677
-2.92,  0, 0, 0, 0, 2451545.699
-16.61, 0, 0, 0, 0, 2454688.310
-11.66, 0, 0, 0, 0, 2454688.389
-12.61, 0, 0, 0, 0, 2454688.400

输出:

#For ordered (by date) output
ordered_dict = collections.OrderedDict(sorted(jd_sigma_map.items()))

for k, v in ordered_dict.items():
    average = float(v/jd_sigma_count[k])
    print("Sigma value for day %s = %0.3f \t(over %d days)\tAverage = %0.3f" 
          % (k, v, jd_sigma_count[k], average))

# Sigma value for day 2000-1-1 = -25.340  (over 2 days)   Average = -12.670
# Sigma value for day 2000-1-2 = -8.840   (over 2 days)   Average = -4.420
# Sigma value for day 2008-8-9 = -40.880  (over 3 days)   Average = -13.627

注意事项:

  • 使用字典可以让我们为每一天“保存”一个 sigma 值。比摆弄 2x2 数组更容易。
  • 输出jd_sigma_map 是一个字典,键是YYYY-MM-DD 格式的日期,值是当天的总sigma 值。我们不关心格式,我们只希望一天中的每个键都唯一
  • 如您所知,我在读取 CSV 期间“即时”进行了所有分析,您也可以将其存储在列表中,然后关闭分析后文件。
  • Python 3 解决方案(对于 Python 2.x,将 print() 更改为 print ...items() 更改为 iteritems()
  • 查看this question对输出字典进行排序(代码中添加)

【讨论】:

  • 到目前为止,代码运行良好。我也将输出保存到一个新文件中。有没有一种方法可以让我看到一天内有多少 sigma_0 值被考虑在内?因为,实际上我需要每天的 sigma_0 值的平均值(而不仅仅是总和)。
  • 不用担心,很高兴我能帮上忙!我已按要求更新了答案-这是解决问题的简单方法。不幸的是,我想不出一个可以利用现有数据结构的“更简洁”的解决方案(例如,将_map 字典更改为具有元组值(value, count)
  • 再次感谢您的帮助。我正在摆弄在整个字典开始之前进行查询的想法。例如,我有第七列的距离值(从 0 到 20 000),我首先让用户回答问题 ["distance = input("Pls type in the distance/ radius:"] 并据此回答sigma_0 值将被累加和平均。这可能吗?
  • 用日期和距离制作钥匙是否可行?像 [dist_key = '%f', '%s-%s-%s' % (row[6], year, month, dd) ] ?
【解决方案2】:
import numpy as np

array = [['-12.42', '2451544.576'],
     ['-12.92', '2451544.576'],
     ['-12.45', '2451544.576'],
     ['-11.66', '2454688.389'],
     ['-12.61', '2454688.389'],
     ['-11.72', '2454688.389']]


matrix = np.asmatrix(array)
print matrix
for (i, j), ele in np.ndenumerate(matrix):
    if j == 1: #SECOND COL
         print i, j, ele

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-06
    • 2019-04-28
    • 2016-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-16
    • 2014-10-10
    相关资源
    最近更新 更多