Python Pandas,将 DataFrame 写入固定宽度的文件(to_fwf?)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16490261/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python Pandas, write DataFrame to fixed-width file (to_fwf?)
提问by jkmacc
I see that Pandas has read_fwf, but does it have something like DataFrame.to_fwf? I'm looking for support for field width, numerical precision, and string justification. It seems that DataFrame.to_csvdoesn't do this. numpy.savetxtdoes, but I wouldn't want to do:
我看到 Pandas 有read_fwf,但它有类似的东西DataFrame.to_fwf吗?我正在寻找对字段宽度、数值精度和字符串对齐的支持。似乎DataFrame.to_csv没有这样做。 numpy.savetxt确实,但我不想这样做:
numpy.savetxt('myfile.txt', mydataframe.to_records(), fmt='some format')
That just seems wrong. Your ideas are much appreciated.
这似乎是错误的。非常感谢您的想法。
回答by Matt Kramer
Until someone implementsthis in pandas, you can use the tabulatepackage:
在有人在 Pandas 中实现这一点之前,您可以使用tabulate包:
import pandas as pd
from tabulate import tabulate
def to_fwf(df, fname):
content = tabulate(df.values.tolist(), list(df.columns), tablefmt="plain")
open(fname, "w").write(content)
pd.DataFrame.to_fwf = to_fwf
回答by Amir Uteuov
For custom format for each column you can set format for whole line. fmt param provides formatting for each line
对于每列的自定义格式,您可以为整行设置格式。fmt 参数为每一行提供格式
with open('output.dat') as ofile:
fmt = '%.0f %02.0f %4.1f %3.0f %4.0f %4.1f %4.0f %4.1f %4.0f'
np.savetxt(ofile, df.values, fmt=fmt)
回答by brandog
Python, Pandas : write content of DataFrame into text File
Python、Pandas:将 DataFrame 的内容写入文本文件
The question aboves answer helped me. It is not the best, but until to_fwfexists this will do the trick for me...
以上问题的答案对我有帮助。它不是最好的,但在to_fwf存在之前,这对我有用......
np.savetxt(r'c:\data\np.txt', df.values, fmt='%d')
or
或者
np.savetxt(r'c:\data\np.txt', df.values, fmt='%10.5f')
回答by leon yin
I'm sure you found a workaround for this issue but for anyone else who is curious... If you write the DF into a list, you can write it out to a file by giving the 'format as a string'.format(list indices) eg:
我确定您找到了解决此问题的方法,但对于其他任何好奇的人...如果您将 DF 写入列表,您可以通过提供“格式为字符串”将其写入文件。列出索引)例如:
df=df.fillna('')
outF = 'output.txt'
dbOut = open(temp, 'w')
v = df.values.T.tolist()
for i in range(0,dfRows):
dbOut.write(( \
'{:7.2f}{:>6.2f}{:>2.0f}{:>4.0f}{:>5.0f}{:6.2f}{:6.2f}{:6.2f}{:6.1f {:>15}{:>60}'\
.format(v[0][i],v[1][i],v[2][i],v[3][i],v[4][i],v[5][i],v[6][i],v[7][i],v[8][i],\
v[9][i],v[10][i]) ))
dbOut.write("\n")
dbOut.close
Just make sure to match up each index with the correct format :)
只需确保将每个索引与正确的格式匹配:)
Hope that helps!
希望有帮助!
回答by zubin patel
found a very simple solution! (Python). In the code snapped I am trying to write a DataFrame to a positional File. "finalDataFrame.values.tolist()" will return u a list in which each row of the DataFrame is turn into an another list just a [['Camry',2019,'Toyota'],['Mustang','2016','Ford']]. after that with the help of for loop and if statement i am trying to set its fix length. rest is obvious!
找到了一个非常简单的解决方案!(Python)。在捕捉的代码中,我试图将数据帧写入位置文件。"finalDataFrame.values.tolist()" 将返回 ua 列表,其中 DataFrame 的每一行都变成另一个列表,只是一个 [['Camry',2019,'Toyota'],['Mustang','2016', '福特']]。之后在 for 循环和 if 语句的帮助下,我试图设置其固定长度。休息是显而易见的!
with open (FilePath,'w') as f:
for i in finalDataFrame.values.tolist():
widths=(0,0,0,0,0,0,0)
if i[2] == 'nan':
i[2]=''
for h in range(7):
i[2]= i[2] + ' '
else:
x=7-len(str(i[2]))
a=''
for k in range(x):
a=a+' '
i[2]=str(i[2])+a
if i[3] == '':
i[3]=''
for h in range(25):
i[3]=i[3]+' '
else:
x = 25 - len(i[3])
print(x)
a = ''
for k in range(x):
a = a + ' '
print(a)
i[3] = i[3] + a
i[4] = str(i[4])[:10]
q="".join("%*s" % i for i in zip(widths, i))
f.write(q+'\n')

