簡體   English   中英

將列表字典轉換為 csv 文件

[英]Converting dictionary of list to csv file

dictionary = {'number': [2.1607142857142856, 1.5160021597156612, 1.0, 6.0],
              'orbital_period': [847.5717667678571, 1796.522108459915, 0.73654, 14002.0], 
              'mass': [2.89239793814433, 4.4152433928281205, 0.0036, 21.42], 
              'distance': [39.760093457943924, 50.97704197461588, 1.35, 354.0], 
              'year': [2007.4732142857142, 5.01701576965303, 1995.0, 2013.0]}

zd = zip(*dictionary.values())
with open('file.csv', 'w') as file:
    writer = csv.writer(file, delimiter=',')
    writer.writerow(dictionary.keys())
    writer.writerows(zd)

如何讀回此文件以查看是否獲得所需的 output? 這甚至會給我 output

我希望 output 在第一列中具有屬性,並將數字列表作為行:

這可能是查看 pandas 的好時機。

import pandas as pd

dictionary = {'number': [2.1607142857142856, 1.5160021597156612, 1.0, 6.0],
              'orbital_period': [847.5717667678571, 1796.522108459915, 0.73654, 14002.0], 
              'mass': [2.89239793814433, 4.4152433928281205, 0.0036, 21.42], 
              'distance': [39.760093457943924, 50.97704197461588, 1.35, 354.0], 
              'year': [2007.4732142857142, 5.01701576965303, 1995.0, 2013.0]}

df = pd.DataFrame.from_dict(dictionary)

df.to_csv('output.csv', index=False)

讀回來

df = pd.read_csv('output.csv')

dataframe 看起來像這樣

     number  orbital_period       mass    distance         year
0  2.160714      847.571767   2.892398   39.760093  2007.473214
1  1.516002     1796.522108   4.415243   50.977042     5.017016
2  1.000000        0.736540   0.003600    1.350000  1995.000000
3  6.000000    14002.000000  21.420000  354.000000  2013.000000

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM