简体   繁体   English

有没有更好的方法可以循环for循环中的多个未知变量?

[英]Is there a better way to loop over multiple unknown variables in a for loop?

So I have this task where I want to print to a text file. 因此,我有要在其中打印到文本文件的任务。 This file includes header information and columns of data with specific names. 该文件包括标头信息和具有特定名称的数据列。 Here is the code: 这是代码:

import numpy as np

data={'dpr_NS_corZFac': [np.nan, np.nan, 35.736231803894043, 36.331412792205811,
               35.694644451141357, 36.576189994812012, 37.236752510070801,
               38.173699378967285, 38.808069229125977, 36.761274337768555,
               30.194313526153564],
    'dpr_HS_corZFac': [np.nan, 38.550984859466553, 37.893826961517334, 40.246520042419434,
             39.204437732696533, 37.227160930633545, 37.364296913146973,
             40.320019721984863, 39.04454231262207, 33.014707565307617,
             27.193448543548584],
    'npol':[np.nan, np.nan, 35.736231803894043, 36.331412792205811,
               35.694644451141357, 36.576189994812012, 37.236752510070801,
               38.173699378967285, 38.808069229125977, 36.761274337768555,
               30.194313526153564] }

datafile_path = '/home/cpabla/data/pandastext.txt'

with open(datafile_path, 'w+') as f:
    f.write('Charanjit is writing this text file.')
    f.write('\t'*4)
    f.write('He continues to write....\n')
    for tag in data:
        f.write('{}\t\t'.format(tag))
    f.write('\n')
    for val1, val2, val3 in zip(data['dpr_NS_corZFac'], data['dpr_HS_corZFac'], data['npol']):
        if np.isnan(val1): val1 = 99.99
        if np.isnan(val2): val2 = 99.99
        if np.isnan(val3): val3 = 99.99
        f.write('{:.2f}'.format(val1))
        f.write('\t'*7)
        f.write('{:.2f}'.format(val2))
        f.write('\t'*7)
        f.write('{:.2f}'.format(val3))
        f.write('\t'*7)
        f.write('\n')

The details of the code is not important as this is simply for testing on my end. 代码的细节并不重要,因为这仅仅是为了我的测试。 Notice how I have a dictionary of lists. 注意我如何有一个列表字典。 I will have an unknown amount of lists in a dictionary and I want to produce a text file of the for given in the example output. 在字典中,列表的数量将是未知的,并且我想生成示例输出中给定的的文本文件。 But, notice how I loop over multiple variables (in this case lists in my dictionary). 但是,请注意我如何遍历多个变量(在本例中为字典中的列表)。 I obviously want to automate this so I dont have to keep adding variables to the for loop. 我显然很想自动执行此操作,因此不必继续向for循环添加变量。 So is there a better way to do this? 那么,有没有更好的方法呢?

Here is the output: 这是输出:

Charanjit is writing this text file.                He continues to write....
dpr_HS_corZFac      dpr_NS_corZFac      npol
99.99                           99.99                           99.99
99.99                           38.55                           99.99
35.74                           37.89                           35.74
36.33                           40.25                           36.33
35.69                           39.20                           35.69
36.58                           37.23                           36.58
37.24                           37.36                           37.24
38.17                           40.32                           38.17
38.81                           39.04                           38.81
36.76                           33.01                           36.76
30.19                           27.19                           30.19

The actual output to a text editor is not like this however. 但是,文本编辑器的实际输出却不是这样。 Each column is under its own header name which is exactly what I want. 每列都在其自己的标题名称下,这正是我想要的名称。 The output is simply to show you what I am trying to do. 输出只是为了向您展示我正在尝试做的事情。

One solution could be : 一种解决方案可能是:

for k in data.keys():
    for val in data[k] :
        if np.isnan(val): val = 99.99
            f.write('{:.2f}'.format(val))
            f.write('\t'*7)
        f.write('\n')

Edit : you're right Akasolace, I've edited my code 编辑:您是对的Akasolace,我已经编辑了我的代码

import numpy as np 

data={'dpr_NS_corZFac': [np.nan, np.nan, 35.736231803894043, 36.331412792205811, 
               35.694644451141357, 36.576189994812012, 37.236752510070801, 
               38.173699378967285, 38.808069229125977, 36.761274337768555, 
               30.194313526153564],
    'dpr_HS_corZFac': [np.nan, 38.550984859466553, 37.893826961517334, 40.246520042419434, 
             39.204437732696533, 37.227160930633545, 37.364296913146973, 
             40.320019721984863, 39.04454231262207, 33.014707565307617, 
             27.193448543548584],
    'npol':[np.nan, np.nan, 35.736231803894043, 36.331412792205811, 
               35.694644451141357, 36.576189994812012, 37.236752510070801, 
               38.173699378967285, 38.808069229125977, 36.761274337768555, 
               30.194313526153564] }

datafile_path = r'D:\TEMP\pandastext.txt'

with open(datafile_path, 'w+') as f:
    f.write('Charanjit is writing this text file.')
    f.write('\t'*4)
    f.write('He continues to write....\n')
    for tag in data:
        f.write('{}\t\t'.format(tag))
    f.write('\n')
    for vals in zip(data['dpr_NS_corZFac'], data['dpr_HS_corZFac'], data['npol']):
        for val in vals:
            if np.isnan(val): val = 99.99
            f.write('{:.2f}'.format(val))
            f.write('\t'*7)
        f.write('\n')

Can you use pandas? 可以用熊猫吗?

Here: 这里:

In [50]: import pandas as pd

In [48]: pd.set_option('precision', 2)

In [51]: df = pd.DataFrame(data)

In [52]: df
Out[52]:
    dpr_HS_corZFac  dpr_NS_corZFac   npol
0              NaN             NaN    NaN
1            38.55             NaN    NaN
2            37.89           35.74  35.74
3            40.25           36.33  36.33
4            39.20           35.69  35.69
5            37.23           36.58  36.58
6            37.36           37.24  37.24
7            40.32           38.17  38.17
8            39.04           38.81  38.81
9            33.01           36.76  36.76
10           27.19           30.19  30.19


In [56]: df.replace(np.NaN, 99.99, inplace=True)

In [57]: print df.to_string()
    dpr_HS_corZFac  dpr_NS_corZFac   npol
0            99.99           99.99  99.99
1            38.55           99.99  99.99
2            37.89           35.74  35.74
3            40.25           36.33  36.33
4            39.20           35.69  35.69
5            37.23           36.58  36.58
6            37.36           37.24  37.24
7            40.32           38.17  38.17
8            39.04           38.81  38.81
9            33.01           36.76  36.76
10           27.19           30.19  30.19

In [58]:

To write to a file (to be complete) 写入文件(完整)

In [59]: with open(r'C:\temp\data.txt', 'w') as f:
             f.write("Whatever you want here")
    ...:     f.write(df.to_string(index=False))
    ...:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM