简体   繁体   English

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

[英]How to format pandas dataframe when writing to csv file?

I have a Pandas dataframe with the following data我有一个包含以下数据的 Pandas 数据框

0 5
1 7
2 3

The first column is the index.第一列是索引。

What is the easiest way to get this written to a csv file (space delimited) so the output will look like this?将其写入 csv 文件(空格分隔)以便输出看起来像这样的最简单方法是什么?

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

By csv file, I mean writing a file like this:通过 csv 文件,我的意思是写一个这样的文件:

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

you can proceed as follows您可以按照以下步骤进行

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)

To have the index as an implicit column in the csv:要将索引作为 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)

gives

0,5
1,7
2,3

or if you have more interesting index values then use或者如果您有更有趣的索引值,则使用

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)

which gives这使

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

to get spaces the use得到空间的使用

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)

which gives这使

0 5
1 7
2 3

although spaces are probably best to avoid.尽管最好避免使用空格。

The closer resemblance to your |header is perhaps与您的|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=' ')

giving给予

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM