简体   繁体   English

如何将此数据写入 .csv 文件?

[英]How do I write this data to a .csv file?

I'm very new to coding and stackoverflow, so please be kind.我对编码和stackoverflow很陌生,所以请善待。 I'm adjusting some code from Tim Supinie ( https://github.com/tsupinie/vad-plotter ) to run through a given time frame and plot hodographs for these times.我正在调整 Tim Supinie ( https://github.com/tsupinie/vad-plotter ) 的一些代码,以在给定的时间范围内运行并绘制这些时间的全线图。 I'll include the code that I think is relevant below.我将在下面包含我认为相关的代码。

def vad_plotter(radar_id, storm_motion='right-mover', sfc_wind=None, time=None, fname=None, local_path=None, 
                cache_path=None, web=False, fixed=False):
    plot_time = None
    if time:
        plot_time = parse_time(time)
    elif local_path is not None:
        raise ValueError("'-t' ('--time') argument is required when loading from the local disk.")

    if not web:
        print("Plotting VAD for %s ..." % radar_id)

    if local_path is None:
        vad = download_vad(radar_id, time=plot_time, cache_path=cache_path)
    else:
        iname = build_has_name(radar_id, plot_time)
        vad = VADFile(open("%s/%s" % (local_path, iname), 'rb'))

    vad.rid = radar_id

    if not web:
        print("Valid time:", vad['time'].strftime("%d %B %Y %H%M UTC"))

    if sfc_wind:
        sfc_wind = parse_vector(sfc_wind)
        vad.add_surface_wind(sfc_wind)

    params = compute_parameters(vad, storm_motion)
    plot_hodograph(vad, params, fname=fname, web=web, fixed=fixed, archive=(local_path is not None))
    return params

def main():
    
    ap = argparse.ArgumentParser()
    ap.add_argument('radar_id', help="The 4-character identifier for the radar (e.g. KTLX, KFWS, etc.)")
    ap.add_argument('-m', '--storm-motion', dest='storm_motion', help="Storm motion vector. It takes one of two forms. The first is either 'BRM' for the Bunkers right mover vector, or 'BLM' for the Bunkers left mover vector. The second is the form DDD/SS, where DDD is the direction the storm is coming from, and SS is the speed in knots (e.g. 240/25).", default='right-mover')
    ap.add_argument('-s', '--sfc-wind', dest='sfc_wind', help="Surface wind vector. It takes the form DDD/SS, where DDD is the direction the storm is coming from, and SS is the speed in knots (e.g. 240/25).")
    ap.add_argument('-t', '--start-time', dest='start_time', help="Start time to plot. Takes the form DD/HHMM, where DD is the day, HH is the hour, and MM is the minute.")
    ap.add_argument('-e', '--end-time', dest='end_time', help="End time to plot. Takes the form DD/HHMM, where DD is the day, HH is the hour, and MM is the minute.")
    ap.add_argument('-f', '--img-name', dest='img_name', help="Name of the file produced.")
    ap.add_argument('-p', '--local-path', dest='local_path', help="Path to local data. If not given, download from the Internet.")
    ap.add_argument('-c', '--cache-path', dest='cache_path', help="Path to local cache. Data downloaded from the Internet will be cached here.")
    ap.add_argument('-w', '--web-mode', dest='web', action='store_true')
    ap.add_argument('-x', '--fixed-frame', dest='fixed', action='store_true')
    args = ap.parse_args()

    np.seterr(all='ignore')
    
    start_time = args.start_time
    end_time = args.end_time
    loop_time = start_time
    minute = timedelta(minutes=1)
    while loop_time <= end_time:
        try:
            vad_plotter(args.radar_id,
                        storm_motion=args.storm_motion,
                        sfc_wind=args.sfc_wind,
                        time=loop_time,
                        fname=args.img_name,
                        local_path=args.local_path,
                        cache_path=args.cache_path,
                        web=args.web,
                        fixed=args.fixed
                        )
        except:
            if args.web:
                print(json.dumps({'error':'error'}))
            else:
                print('This time does not exist. Continuing to next time.')
                #raise
        loop_time_dt = datetime.strptime(loop_time, '%Y-%m-%d/%H%M')
        loop_time_dt += minute
        loop_time = datetime.strftime(loop_time_dt, '%Y-%m-%d/%H%M')
           
if __name__ == "__main__":
    main()

I have that part working, but I would also like to write the data from params to a csv file.我有那部分工作,但我也想将参数中的数据写入 csv 文件。 When I print params for a single time, I get this:当我一次打印参数时,我得到了这个:

{'bunkers_right': (array(236.340564), 44.8685241699178), 
'bunkers_left': (array(195.94869697), 32.97530676031822), 
'mean_wind': (array(219.36132122), 36.5865434082231), 
'storm_motion': (array(236.340564), 44.8685241699178), 
'critical': 48.86976309962911, 
'shear_mag_1000m': 26.304381854688497, 
'shear_mag_3000m': 38.92926998656143, 
'shear_mag_6000m': 51.945102332633894, 
'srh_1000m': -168.06515362413353, 
'srh_3000m': -172.50414403226904}

And params['srh_1000m'] would give the value -168.06515362413353. params['srh_1000m'] 将给出值 -168.06515362413353。 I'd like for the csv to look somewhat like this, but with all the parameters instead of the shorter example I'll give:我希望 csv 看起来有点像这样,但是我将给出所有参数而不是更短的示例:

time  shear_mag_1000m     shear_mag_3000m     shear_mag_6000m   srh_1000m     srh_3000m
2100  26                  32                  56                 -172          -212
2200  32                  34                  64                 -189          -232

I don't know how to do this or which function I would put the new code in. Any help is appreciated, and the full set of code can be found in the link I included earlier if needed.我不知道如何执行此操作,也不知道我会将新代码放入哪个函数。感谢您提供任何帮助,如果需要,可以在我之前包含的链接中找到完整的代码集。

I think working with pandas would help:我认为与熊猫合作会有所帮助:

import pandas as pd

dic = {'bunkers_right': (array(236.340564), 44.8685241699178), 
       'bunkers_left': (array(195.94869697), 32.97530676031822), 
       'mean_wind': (array(219.36132122), 36.5865434082231), 
       'storm_motion': (array(236.340564), 44.8685241699178), 
       'critical': 48.86976309962911, 
       'shear_mag_1000m': 26.304381854688497, 
       'shear_mag_3000m': 38.92926998656143, 
       'shear_mag_6000m': 51.945102332633894, 
       'srh_1000m': -168.06515362413353, 
       'srh_3000m': -172.50414403226904}

cols = ['time', 'shear_mag_1000m', 'shear_mag_3000m', 'shear_mag_6000m', 'srh_1000m', 'srh_3000m']
new_dic = {key: dic[key] for key in dic.keys() if key in cols}

df = pd.DataFrame.from_dict(new_dic, orient='index').T
df.to_csv('mydata.csv')

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

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