如何从txt文件中读取数据到行和列中进行平均计算Python

How to read data from a txt file into rows and columns for avergae calculatins Python

所以我正在使用 PIV (openPiv) 来处理图像。处理并保存数据后,我得到一个包含三列 x y V:

的 .txt 文件

x: 44 88 132 44 88 132

y: 100 100 100 50 50 50

五:5 0 2 3 6 7

我需要绘制 x 与 V 的关系图,但对于相同的 x 值,我有 2 个 V 值,所以我想对 2 个取平均值。 因此,我试图在 python 中编写一个代码,该代码可以读取文件中 x 的值并带回所有相关的 V 值,以便我可以对它们求和和求平均值。假设它读取 x=44,转到文件并选择 x=44、v=5 和 3。

非常感谢帮助 非常感谢

fl=open("fileq.txt",'r+')
read_file=fl.read()
ls2=[]
x=0
y=1
V=2
ls_of_ls=[]
sepr=read_file.split('\n')
for items in sepr:
    items=items.split(':')[1]
    ls2.append(items)
for items in ls2:
    ls_of_ls.append(list(map(int,items.split())))
len_inp=len(ls_of_ls[x])
k=int(input("for value x: "))
print("V= ",end='')
for i in range(len_inp):
    if k==ls_of_ls[x][i]:
        print(ls_of_ls[V][i],end=" ")

我已经根据文本文件中的给定格式编写了这段代码,即

x: 44 88 132 44 88 132

y: 100 100 100 50 50 50

V: 5 0 2 3 6 7

只需将 fileq.txt 替换为您的文件

如果你想要垂直格式的代码,我可以为你做。

import pandas as pd
file=pd.read_csv('file.csv', sep='\t')
velocity_along_x=file.groupby('x')['V'].mean()
velocity_along_x.plot()

我找到了一种更简单的方法 Pandas