【问题标题】:How can I write a file with a data stored in a dictionary?如何使用存储在字典中的数据编写文件?
【发布时间】:2019-05-14 21:57:51
【问题描述】:

我将数据存储在字典中,如下所示:

Data = {'Key1': np.array([0., 3., 4., ..., 0., 4., 5.]),
'Key2': np.array([2., 1., 6., ..., 2., 4., 5.]),
'Key3': np.array([0., 0., 0., ..., 1., 1., 0.]),
'Key4': np.array([0., 0., 0., ..., 0., 2., 0.]),
'Key5': np.array([0., 1., 2., ..., 0., 0., 0.])}

现在我需要创建一个文件并将这些数据以这样的列的形式存储:

Data.txt
Key1   Key2   Key3   Key4   Key5
0       2      0      0      0
3       1      0      0      1
4       6      0      0      2
...

任何帮助将不胜感激。谢谢!

【问题讨论】:

  • 如果您搜索“Python 读取存储数据”这一短语,您会找到比我们在此处的答案中更好地解释它的资源。
  • 下次我会尽量记住这一点,感谢您的反馈

标签: python file dictionary


【解决方案1】:

Pandas 在这方面做得很好:

import pandas as pd
pd.DataFrame.from_dict(your_data).to_csv("data.csv")

【讨论】:

    【解决方案2】:

    创建一个 Pandas 数据框并将其写入文件:

    >>> import pandas as pd
    >>> df = pd.DataFrame.from_dict(Data)
    >>> df.to_csv(r'Data.txt', index=False, header=True, sep='\t')
    >>> df
    Key1   Key2   Key3   Key4   Key5
    0       2      0      0      0
    3       1      0      0      1
    4       6      0      0      2
    

    【讨论】:

      猜你喜欢
      • 2016-03-15
      • 2017-08-16
      • 1970-01-01
      • 2016-10-23
      • 2018-10-08
      • 1970-01-01
      • 1970-01-01
      • 2018-07-17
      • 1970-01-01
      相关资源
      最近更新 更多