写入数据帧到CSV与在熊猫
问题描述:
行名的附加头名
我有以下的数据帧:写入数据帧到CSV与在熊猫
In [18]: import pandas as pd
In [32]: df = pd.DataFrame.from_items([("A\tbar", [1, 2, 3]), ("B\tfoo" , [4, 5, 6])],orient='index', columns=['one', 'two', 'three'])
In [33]: df
Out[35]:
one two three
A\tbar 1 2 3
B\tfoo 4 5 6
In [34]: df.to_csv("tmp.csv" , sep='\t', encoding='utf-8', doublequote=False)
最后的书面文件看起来是这样的(注意行名称双引号仍然存在,我们也倒是想删除):
In [34]: !cat tmp.csv
one two three
"A bar" 1 2 3
"B foo" 4 5 6
我想要做的是名字,看起来像这样的行名称的列 最终创建的文件(tmp.csv):
alpha othername one two three
A bar 1 2 3
B foo 4 5 6
这是干什么的?
答
感谢BrenBarn为0
df = pd.DataFrame.from_items([("A\tbar", [1, 2, 3]), ("B\tfoo" , [4, 5, 6])],orient='index', columns=['one', 'two', 'three'])
df['col_a'] = df.index
lista = [item.split('\t')[0] for item in df['col_a']]
listb = [item.split('\t')[1] for item in df['col_a']]
df['col_a'] = lista
df['col_b'] = listb
cols = df.columns.tolist()
cols = cols[-2:] + cols[:-2]
df = df[cols]
df.to_csv('filename', index=False)
如果你想他们是单独的列,你为什么不创建它们作为单独的列,而不是在其标签的单个列? – BrenBarn 2014-11-21 05:21:32
在实际情况下,创建行名称更复杂。我想保持简单的问题陈述。 – neversaint 2014-11-21 05:23:31
基本的答案是,你不能命名你的rownames的列,因为你的行名没有列。你的索引只是一堆恰好有标签的字符串,但熊猫不知道它们都有标签。你可以给第一列提供一个带有标签的名称(即将其命名为“alpha \ tothername”)。 – BrenBarn 2014-11-21 05:25:59