gpt4 book ai didi

python - 从Python中随机目录的文本文件中读取数据

转载 作者:太空宇宙 更新时间:2023-11-03 20:31:54 25 4
gpt4 key购买 nike

我想从具有随机目录的文本文件中读取数据(数字)。文本文件包含类似这样的单词和数字,我如何提取这些列。

Start Time:  7/28/2019 7:58:06 PM         Time Completed:  7/28/2019 8:21:24 PM     Elapsed Time:  00:23:17
Sample ID: 190728-MTJ-IP

***DATA***

Field(Oe) Moment(emu)
987.95878 0.000046470297
963.27719 0.000046452876
938.57541 0.000046659299
913.89473 0.000046416303
889.19093 0.000046813005
864.50576 0.000047033128
839.80973 0.000046368291
815.12703 0.000046888714
790.45031 0.000045933749
765.75385 0.00004716459
741.05444 0.000046405491

我打算使用这个,但我很困惑,我应该放在什么索引上:

def txtread(filepath):
data = []
with open(filepath+'.txt', 'r') as readfile:
datalines = readfile.readlines()
for lines in datalines:
temp = lines.strip('\t\n').split(',')
temp = np.array(temp[:],dtype=float)
data = np.array(data[0::2])
H = data[:,0]
M = data[:,1]

最佳答案

Pandas read_csv方法有一堆参数来处理所有这些:

>>> import pandas as pd
>>> pd.read_csv('temp.txt', skiprows=5, delim_whitespace=True)

Field(Oe) Moment(emu)
0 987.95878 0.000046
1 963.27719 0.000046
2 938.57541 0.000047
3 913.89473 0.000046
4 889.19093 0.000047
5 864.50576 0.000047
6 839.80973 0.000046
7 815.12703 0.000047
8 790.45031 0.000046
9 765.75385 0.000047
10 741.05444 0.000046

pd.read_csv 的输出是一个DataFrame。如果您更喜欢使用 numpy 数组,

df = pd.read_csv(...)
np_data = df.values

关于python - 从Python中随机目录的文本文件中读取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57446733/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com