如何处理在不同行中有多个列的.dat文件数据帧?

2024-10-01 11:32:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试从.dat文件导入数据。 这些文件具有以下结构(每个测量有几百个):

#-G8k5perc
#acf0
4e-07 1.67466
8e-07 1.57061
...
13.4217728 0.97419
&
#fit0
2.4e-06 1.5376
3.2e-06 1.5312
...
13.4 0.99578
&
...
#cnta0
@with g2
#cnta0
0 109.74
0.25 107.97
...
19.75 104.05
#rate0 107.2

我试过:
(一)

df = pd.read_csv("G8k5perc-1.dat")

只给出一列。
添加,sep=' ',delimiter=' ',delim_whitespace=True会导致 ParserError: Error tokenizing data. C error: Expected 1 fields in line 3, saw 2

2)
我见过有人使用:
from string import find, rfind, split, strip
这会引发错误:ImportError: cannot import name 'find' from 'string'对于所有四个变量。

3)
创建切片并在以后更改它们也不会起作用:

acf=df[1:179]
acf["#-G8k5perc"]= acf["#-G8k5perc"].str.split(" ", n = 1, expand = True)
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
  app.launch_new_instance()

关于如何为文件中的每组数据(acf0、fit0等)获取两列,您有什么想法吗


Tags: 文件数据infromimporttruedfstring
1条回答
网友
1楼 · 发布于 2024-10-01 11:32:45

不能将csv读取器与数据格式.dat一起使用。 请尝试以下代码:

import csv

datContent = [i.strip().split() for i in open("./yourdata.dat").readlines()]

with open("./yourdata.csv", "wb") as f:
    writer = csv.writer(f)
    writer.writerows(datContent)

然后尝试使用熊猫创建新列:

import pandas as pd

def your_func(row):
    return row['x-momentum'] / row['mass']

columns_to_keep = ['#time', 'x-momentum', 'mass']
dataframe = pd.read_csv("./yourdata.csv", usecols=columns_to_keep)
dataframe['new_column'] = dataframe.apply(your_func, axis=1)

print dataframe

用输入文件名替换yourdata.csv

相关问题 更多 >