如何将数据从熊猫数据帧写入平面文件,每行一个值

时间:2019-06-23 09:43:15

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

我在CSV文件中有以下数据

int

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

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

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

1 个答案:

答案 0 :(得分: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 ...开头。