从大型文本文件创建多个数据帧

2024-04-27 03:56:18 发布

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

使用Python,如何将文本文件分解为数据帧,其中每84行是一个新的、不同的数据帧?第一列x_ft是每84行的相同值,然后在接下来的84行中递增5 ft。我需要行中每个相同的x\u ft值和其他两列(depth\u ft和vel\u ft)对应的值也在新的数据帧中。
我的文本文件格式如下:

   x_ft     depth_ft    vel_ft_s
0   270     3535.755    551.735107
1   270     3534.555    551.735107
2   270     3533.355    551.735107
3   270     3532.155    551.735107
4   270     3530.955    551.735107
.
.
33848   2280    3471.334    1093.897339
33849   2280    3470.134    1102.685547
33850   2280    3468.934    1113.144287
33851   2280    3467.734    1123.937134

我试过很多很多不同的方法,但总是遇到错误,非常感谢你的帮助


Tags: 数据方法格式错误文本文件depthft行是
2条回答

您可以获取索引来分割数据:

rows = 84
datasets = round(len(data)/rows) # total datasets
index_list = []

for index in data.index:
    x = index % rows    
    if x == 0:
        index_list.append(index)

print(index_list)

因此,按索引拆分原始数据集:

l_mod = index_list + [max(index_list)+1]
dfs_list = [data.iloc[l_mod[n]:l_mod[n+1]] for n in range(len(l_mod)-1)]

print(len(dfs_list))

输出

print(type(dfs_list[1]))
# pandas.core.frame.DataFrame

print(len(dfs_list[0]))
# 84

我建议查看pandas.read_table,它会自动输出一个数据帧。执行此操作后,您可以通过执行以下操作来隔离要分离的数据帧的行(每84行):

df = #Read txt datatable with Pandas
arr = []
#This gives you an array of all x values in your dataset
for x in range(0,403):
    val = 270+5*x
    arr.append(val)

#This generates csv files for every row with a specific x_ft value with its corresponding columns (depth_ft and vel_ft_s)
for x_value in arr:
    tempdf = df[(df['x_ft'])] = x_value
    tempdf.to_csv("df"+x_value+".csv")

相关问题 更多 >