我想将数据从文本文件格式化为特定格式。我的数据文件包含超过120000行,但是我在这里发布了截断的数据。数据文件具有用于不同频率(此处为3行中的3个频率)的R,L,G,C数据。该文件只有2列,第一列是“ Freq”,第二列是RLGC数据之一。现在,我想将数据处理为另一种格式(例如,目标.txt)。这是数据的link。我想将其转换为目标文件,例如this

这是我的代码:

import pandas as pd

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

#boolean mask for identify columns of new df
m = df['v'].str.endswith('R', 'L', 'G', 'C')
#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.columns = [x.replace('R','R1:1').replace('L','L1:1').replace('G','G1:1').replace('C','C1:1') for x in df.columns]
df.to_csv('target.txt', index=False, sep='\t')


但是它给出了以下错误:

TypeError: wrapper3() takes from 2 to 3 positional arguments but 5 were given


谁能帮助我将其格式化为目标文件。

现在,我需要目标文件以外的其他格式。我需要格式化为“ target_2.txt”。这是还需要的另一种异常类型的格式。您可以看到,R1:1,L1:1,G1:1和C1:1数据中的每个数据现在看起来都像是一个数组块(尽管不是数组)。如果仔细观察,对于freq,它应命名为FORMAT Freq,然后是tab,然后是:,再是tab,然后是R1:1。如果看到,它将类似于-FORMAT Freq+tab+:+tab+R1:1。然后是new line,然后是2 tabs,然后是L1:1。然后再次是new line,然后是2 tabs,然后是G1:1。最后,对于C1:1也是一样。在该空白行之后,然后跟随第一行数据,第二行数据并继续。数据值将根据标题行。

该第二个目标文件怎么做?

我正在使用Spyder 3.2.6,其中嵌入了python 3.6.4 64位。

最佳答案

您不能以这种方式使用str.endswith。对于您似乎要寻找的东西,我想说str.contains是一个更好的解决方案,您可以在其中寻找R或L或...,例如:

m = df['v'].str.contains('R|L|G|C')


然后输入您的代码,直到pivot。我在pivot行中由于由nan行引起的错误,因此您可能需要dropna并且可以同时rename列:

df = (df.dropna().pivot('freq', 'g', 'v').rename_axis(None, axis=1)
        .reindex(columns=cols).reset_index()
        .rename(columns={col:'{}1:1'.format(col) for col in cols}))


df看起来像:

       freq      R1:1      L1:1      G1:1      C1:1
0  0.00E+00  2.66E+00  3.00E-07  2.76E-16  1.58E-10
1  1.00E+06  2.89E+00  3.10E-07  1.72E-05  1.46E-10
2  2.00E+06  2.98E+00  3.13E-07  3.43E-05  1.45E-10
3  3.00E+06  3.07E+00  3.15E-07  5.15E-05  1.44E-10

关于python - Python中的数据格式化和操作,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51848977/

10-09 17:07
查看更多