写入csv文件时如何格式化pandas数据框?

How to format pandas dataframe when writing to csv file?

我有一个 Pandas 数据框,其中包含以下数据

0 5
1 7
2 3

第一列是索引。

将此写入 csv 文件(space 分隔)以便输出看起来像这样的最简单方法是什么?

|index 0 |features 5
|index 1 |features 7
|index 2 |features 3

csv 文件,我的意思是写一个这样的文件:

test.to_csv('test_map2.txt', sep=' ', header=None, index=False)

要将索引作为 csv 中的隐式列:

import pandas as pd
import io
df = pd.DataFrame(dict(data=[5, 7, 3]))
with io.open('df.csv', 'wb') as file: df.to_csv(file, header=False)

给予

0,5
1,7
2,3

或者如果您有更有趣的索引值,则使用

import pandas as pd
import io
df = pd.DataFrame(dict(data=[5, 7, 3]))
df.reset_index(inplace=True)
with io.open('df.csv', 'wb') as file: df.to_csv(file)

这给出了

,index,data
0,0,5
1,1,7
2,2,3

获取空间 使用

import pandas as pd
import io
df = pd.DataFrame(dict(data=[5, 7, 3]))
df.index.rename
with io.open('df.csv', 'wb') as file: df.to_csv(file, sep=" ", header=False)

这给出了

0 5
1 7
2 3

尽管最好避免使用空格。

与您的|header更相似的可能是

import pandas as pd
import io
df = pd.DataFrame(dict(data=[5, 7, 3]))
df.index.rename
df.reset_index(inplace=True)
for col in df.columns:
    df[col] = df[col].apply(lambda x: '|' +  col + ' ' + str(x))
with io.open('df.csv', 'wb') as file: df.to_csv(file, sep=" ", header=False, index=False, quotechar=' ')

给予

 |index  0   |data  5 
 |index  1   |data  7 
 |index  2   |data  3 

您可以进行如下操作

test.index = test.index.map(lambda x:"|index " + str(x))
test.ix[:,0] = test.ix[:,0].apply(lambda x:'|features ' + str(x))
test.to_csv('test_map2.txt', sep=' ', header=None, index=False)