简体   繁体   中英

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. 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

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))
    ...:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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