How to write a pandas Series to CSV as a row, not as a column?

血红的双手。 提交于 2021-01-27 01:15:16

问题


I need to write a pandas.Series object to a CSV file as a row, not as a column. Simply doing

the_series.to_csv( 'file.csv' )

gives me a file like this:

record_id,2013-02-07
column_a,7.0
column_b,5.0
column_c,6.0

What I need instead is this:

record_id,column_a,column_b,column_c
2013-02-07,7.0,5.0,6.0

This needs to work with pandas 0.10, so using the_series.to_frame().transpose() is not an option.

Is there a simple way to either transpose the Series, or otherwise get it written as a row?

Thanks!


回答1:


You can just use the DataFrame constructor (rather than to_frame):

In [11]: pd.DataFrame(s).T
Out[11]: 
record_id   column_a  column_b  column_c
2013-02-07         7         5         6



回答2:


If you do not want line breaks:

    df = pd.DataFrame({'record_id' : ['column_a','column_b','column_c'],
                       '2013-02-07' : [7.0, 5.0, 6.0]})
    str_1 = ', '.join(df.record_id.tolist())
    str_2 = ', '.join(str(x) for x  in df['2013-02-07'].tolist())

    print('record_id, ' + str_1)
    print('2013-02-07, ' + str_2)


来源:https://stackoverflow.com/questions/21320405/how-to-write-a-pandas-series-to-csv-as-a-row-not-as-a-column

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!