I need to write a pandas.Series
object to a CSV file as a row, not as a column. Simply doing
我需要将pandas.Series对象写为CSV文件作为行,而不是列。干脆做
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.
这需要使用pandas 0.10,所以使用the_series.to_frame()。transpose()不是一个选项。
Is there a simple way to either transpose the Series, or otherwise get it written as a row?
是否有一种简单的方法可以转换系列,或者将其写成一行?
Thanks!
谢谢!
2 个解决方案
#1
13
You can just use the DataFrame constructor (rather than to_frame):
您可以使用DataFrame构造函数(而不是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
0
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)
#1
13
You can just use the DataFrame constructor (rather than to_frame):
您可以使用DataFrame构造函数(而不是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
0
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)