首页 > 解决方案 > 使用 pandas 读取 .txt 文件并根据一列中的某个范围对其进行切片

问题描述

我有多个 .txt 文件,这些文件充满了垃圾数据,并且只需要其中的一部分,基于文件之间的某些变化范围。我还在学习 Python,经验还不是很丰富。

我正在使用 VS 代码 1.50 和 Python 3.8.1

我的数据样本:https ://pastebin.com/kZm1spnz

我的第一个问题是阅读 .txt 文件,这是我最初所做的:

import pandas as pd
import os

#Reading my data
Data = pd.read_csv('Data_01.txt')

我不明白为什么即使 python 脚本与 .txt 文件位于同一文件夹中,它也会出错。

错误:

---------------------------------------------------------------------------
FileNotFoundError                         Traceback (most recent call last)
<ipython-input-28-436477220532> in <module>
      3 
      4 #Reading my data
----> 5 Data = pd.read_csv("Data_01.txt", sep="\t", names=["Depth", "Porosity"])

~\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\io\parsers.py in read_csv(filepath_or_buffer, sep, delimiter, header, names, index_col, usecols, squeeze, prefix, mangle_dupe_cols, dtype, engine, converters, true_values, false_values, skipinitialspace, skiprows, skipfooter, nrows, na_values, keep_default_na, na_filter, verbose, skip_blank_lines, parse_dates, infer_datetime_format, keep_date_col, date_parser, dayfirst, cache_dates, iterator, chunksize, compression, thousands, decimal, lineterminator, quotechar, quoting, doublequote, escapechar, comment, encoding, dialect, error_bad_lines, warn_bad_lines, delim_whitespace, low_memory, memory_map, float_precision)
    684     )
    685 
--> 686     return _read(filepath_or_buffer, kwds)
    687 
    688 

~\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\io\parsers.py in _read(filepath_or_buffer, kwds)
    450 
    451     # Create the parser.
--> 452     parser = TextFileReader(fp_or_buf, **kwds)
    453 
    454     if chunksize or iterator:

~\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\io\parsers.py in __init__(self, f, engine, **kwds)
    934             self.options["has_index_names"] = kwds["has_index_names"]
    935 
--> 936         self._make_engine(self.engine)
    937 
    938     def close(self):

~\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\io\parsers.py in _make_engine(self, engine)
   1166     def _make_engine(self, engine="c"):
   1167         if engine == "c":
-> 1168             self._engine = CParserWrapper(self.f, **self.options)
   1169         else:
   1170             if engine == "python":

~\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\io\parsers.py in __init__(self, src, **kwds)
   1996         kwds["usecols"] = self.usecols
   1997 
-> 1998         self._reader = parsers.TextReader(src, **kwds)
   1999         self.unnamed_cols = self._reader.unnamed_cols
   2000 

pandas\_libs\parsers.pyx in pandas._libs.parsers.TextReader.__cinit__()

pandas\_libs\parsers.pyx in pandas._libs.parsers.TextReader._setup_parser_source()

FileNotFoundError: [Errno 2] No such file or directory: 'Data_01.txt'

我通过使用我的数据文件的完整路径来修复它,但我不明白需要完整路径,如下所示:

import pandas as pd
import os

#Reading my data
Data = pd.read_csv(r"C:\Users\User\Desktop\Projects\SDP\Data_01.txt", sep="\t", names=["Depth", "Porosity"])

现在,当切片我的数据时,我不想使用索引,即“iloc”和“loc”,以保持我的代码可读和易于操作并重新申请其他文件,也许使用 for 循环来扫描它们一次运行。所以我首先使用以下方法进行了测试:

Data_result_1 = Data[Data['Depth'] >= 7711]

这可行,但是,我希望在同一行中使用一个附加条件,它在深度 = 7786 处停止,即我的范围。但它不起作用,这是我写的失败的代码:

Data_result_1 = Data[Data['Depth'] >= 7711 and Data['Depth'] <= 7786]

有没有办法在不创建新代码行的情况下使用嵌套条件,我能够达到我想要的结果,因为它感觉没有必要,坦率地说,很难看。这是有效的:

Data_result_1 = Data[Data['Depth'] >= 7711 ] 
Data_result_1 = Data_result_1[Data_result_1['Depth'] <= 7786]

标签: pythonpython-3.xpandasdataframe

解决方案


您应该使用 & 而不是 and:

Data_result_1 = Data[ (Data['Depth'] >= 7711) & (Data['Depth'] <= 7786)]

推荐阅读