【问题标题】:How to write data from pandas dataframe to a flat file with one value per row如何将数据从 pandas 数据帧写入每行一个值的平面文件
【发布时间】:2019-06-23 09:43:15
【问题描述】:

我在 CSV 文件中有如下数据

Date    Temperature_city_1  Temperature_city_2  Temperature_city_3  Which_destination
20140910    80  32  40  1
20140911    100 50  36  2
20140912    102 55  46  1
20140912    60  20  35  3
20140914    60  20  32  3
20140914    60  57  42  2

我需要以下格式的平面文件中的这些数据

Date
Temperature_city_1
Temperature_city_2
Temperature_city_3
Which_destination

20140910
80
32
40
1

20140911
100
50
36
2
...

我正在尝试使用 pandas 并将这些数据写入平面文件,但没有运气。 尝试了示例代码,但没有运气

【问题讨论】:

    标签: python pandas dataframe file-io flat-file


    【解决方案1】:

    您实际上可以使用标准的to_csv 方法来做到这一点。您只需将sep 参数指定为\n 并将line_terminator 指定为\n\n

    import pandas as pd
    
    df = pd.DataFrame({'Date': {0: 20140910,
      1: 20140911,
      2: 20140912,
      3: 20140912,
      4: 20140914,
      5: 20140914},
     'Temperature_city_1': {0: 80, 1: 100, 2: 102, 3: 60, 4: 60, 5: 60},
     'Temperature_city_2': {0: 32, 1: 50, 2: 55, 3: 20, 4: 20, 5: 57},
     'Temperature_city_3': {0: 40, 1: 36, 2: 46, 3: 35, 4: 32, 5: 42},
     'Which_destination': {0: 1, 1: 2, 2: 1, 3: 3, 4: 3, 5: 2}})
    
    df.to_csv('my_csv_file.csv', sep='\n', line_terminator='\n\n', index=False)
    

    生成的文件将如下所示:

    Date
    Temperature_city_1
    Temperature_city_2
    Temperature_city_3
    Which_destination
    
    20140910
    80
    32
    40
    1
    
    20140911
    100
    50
    36
    2
    
    20140912
    102
    55
    46
    1
    ...
    

    我将index 设置为False,这样每组值就不会以索引0、1、2 ...

    【讨论】:

      猜你喜欢
      • 2023-03-22
      • 1970-01-01
      • 2021-09-06
      • 2022-07-28
      • 2015-09-08
      • 2021-11-09
      • 2016-03-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多