【问题标题】:How to skip a point in a .csv file if it is larger than x?如果 .csv 文件中的某个点大于 x,如何跳过它?
【发布时间】:2022-09-24 12:09:19
【问题描述】:

我有一些需要忽略的异常值的数据,但我正在努力找出如何做到这一点。我需要删除/忽略超过 500 的数据。到目前为止,以下是我的代码:

import pandas as pd 
import matplotlib

#convert the files to make sure that only the data needed is selected
INPUT_FILE = \'data.csv\'
OUTPUT_FILE = \'machine_data.csv\'
PACKET_ID = \'machine\'

with open(INPUT_FILE, \'r\') as f:
data = f.readlines()
with open(OUTPUT_FILE, \'w\') as f:
for datum in data:
    if datum.startswith(PACKET_ID):
        f.write(datum)

#read the data file
df = pd.read_csv(OUTPUT_FILE, header=None, usecols=[2,10,11,12,13,14])
#plotting the conc
fig,conc = plt.subplots(1,1)
lns1 = conc.plot(df[2],df[11],color=\"g\", label=\'Concentration\')

如您所见,我选择了我需要的某些列,但在 [11] 中我只需要小于 500 的数据。

  • 您能否为您的df 提供一个可重现的示例?理想情况下,您不应该像现在这样对df 进行切片,而是应该使用loc, iloc, at, iat 函数。
  • @guin0x 这是老师给我的,它在我的代码中运行良好,是我迄今为止唯一的代码。
  • 我了解,但为了您以后的参考,请尽量避免。检查this post了解更多信息

标签: python pandas matplotlib


【解决方案1】:

为了忽略列 df[11] 大于 500 的异常值,请尝试以下操作:

df[11] = df[11].where(df[11] <= 500).dropna()

来源:DataFrame.where()

【讨论】:

  • 非常感谢。现在的数据噪音小了很多。
【解决方案2】:

您只需要按该列过滤您的数据框 喜欢 :

df = df[(df[11] <= 500)]

您的代码将如下所示:

import pandas as pd 
import matplotlib

#convert the files to make sure that only the data needed is selected
INPUT_FILE = 'data.csv'
OUTPUT_FILE = 'machine_data.csv'
PACKET_ID = 'machine'

with open(INPUT_FILE, 'r') as f:
data = f.readlines()
with open(OUTPUT_FILE, 'w') as f:
for datum in data:
    if datum.startswith(PACKET_ID):
        f.write(datum)

#read the data file
df = pd.read_csv(OUTPUT_FILE, header=None, usecols=[2,10,11,12,13,14])

# filter your data HERE:
df = df[(df[11] <= 500)]

#plotting the conc
fig,conc = plt.subplots(1,1)
lns1 = conc.plot(df[2],df[11],color="g", label='Concentration')

【讨论】:

  • 如果我需要将这个说法应用于小于 0 的值,然后是超过 500 的其他值,我可以使用相同的代码并简单地将其操作到我需要的值吗? (很抱歉没有包括在主要问题中,我刚刚考虑过!)
  • 这是一个通用过滤器行:df = df[(df[11] &gt;= 0) &amp; (df[11] &lt;= 500)] 对于第 11 列的 0 到 500 之间的值,以任何适合您的方式进行更改。希望有帮助! (顺便说一下,里面的值是条件,你想加多少就加多少,这里我放两个你看)
  • 非常感谢您的帮助!生成的数据现在噪音小了很多!谢谢!
猜你喜欢
  • 2020-08-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-26
  • 2021-07-14
  • 1970-01-01
  • 1970-01-01
  • 2015-09-18
相关资源
最近更新 更多