【问题标题】:Changing only header in text file before saving it in a new file in Python在将文本文件保存到 Python 中的新文件之前仅更改文本文件中的标题
【发布时间】:2018-08-14 14:01:50
【问题描述】:

我只想更改我的数据文件的标题行,然后再将其保存到格式化后的新文件中。我的数据充满了指数浮动数据。我正在使用嵌入了 python 3.6.4 64 位的 Spyder 3.2.6。

这是我的数据文件link。它被截断,因为每个 R、L、G、C 字段有 3001 行,最终在原始数据文件中总共有 480062 行。

我的数据格式化代码如下:

import pandas as pd

#create DataFrame from csv with columns f and v 
df = pd.read_csv('data.txt', sep="\s+", names=['freq','v'])

#boolean mask for identify columns of new df   
m = df['v'].str.endswith(')')
#new column by replace NaNs by forward filling
df['g'] = df['v'].where(m).ffill()
#get original ordering for new columns
cols = df['g'].unique()
#remove rows with same values in v and g columns
df = df[df['v'] != df['g']]
#reshape by pivoting with change ordering of columns by reindex
df = df.pivot('freq', 'g', 'v').rename_axis(None, axis=1).reindex(columns=cols).reset_index()


df.to_csv('target.txt', index=False, sep='\t')

现在目标文件保存为“target.txt”,其中标题行如下:

freq    R(1,1)  R(1,2)  R(2,1)  R(2,2)  L(1,1)  L(1,2)  L(2,1)  L(2,2)  G(1,1)  G(1,2)  G(2,1)  G(2,2)  C(2,2)  C(1,1)  C(1,2)  C(2,1)

在这里您可以看到每一列都由一个“制表符”分隔。标题行是这样的,因为它从输入文件中获取字符串或数据,而输入文件数据字符串就是这样。

现在我希望我的标题行有点不同,因为它在下面进行进一步处理。您能帮我在将我的数据保存到新文件“target.txt”之前如何将其更改为标题行下方吗?

Freq    R1:1    R1:2    R2:1    R2:2    L1:1    L1:2    L2:1    L2:2    G1:1    G1:2    G2:1    G2:2    C1:1    C1:2    C2:1    C2:2

【问题讨论】:

  • 你能从data.txt发布一个小样本吗?另外,我不太明白你的问题。保存和重新分配标头应该非常简单(请参阅stackoverflow.com/questions/19482970/…
  • @MikePalmice 感谢您的回复。我已经为每个归档的数据添加了截断数据的公共链接。

标签: python pandas dataframe data-manipulation dataformat


【解决方案1】:

对于这种特定情况,您可以像这样重命名标题

df.columns = [x.replace('(','').replace(')','').replace(',',':') for x in df.columns]

在将数据框保存到 csv 之前。

【讨论】:

    猜你喜欢
    • 2014-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-13
    • 2014-10-03
    • 2018-04-24
    • 2012-09-27
    • 1970-01-01
    相关资源
    最近更新 更多