问题
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