gpt4 book ai didi

python-3.x - 使用 python(或 pandas dataframe)在某个 x 范围内切片数据的一部分?

转载 作者:行者123 更新时间:2023-12-05 02:18:20 24 4
gpt4 key购买 nike

我在 python 3.x 中使用附加运算符时遇到了问题。在我的 python 代码中,我试图删除 y 值为 0 的数据点。我的数据如下所示:

x          y
400.01 0.000e0
420.02 0.000e0
450.03 10.000e0
48.04 2.000e0
520.05 0.000e0
570.06 0.000e0
570.23 5.000e0
600.24 0.000e0
620.25 3.600e-1
700.26 8.400e-1
900.31 2.450e0

我想提取属于某个 x 范围内的数据。例如,我想获取 x 和 y 值,其中 x 大于 520 但小于 1000。

期望的输出看起来像..

  x        y
520.05 0.000e0
570.06 0.000e0
570.23 5.000e0
600.24 0.000e0
620.25 3.600e-1
700.26 8.400e-1
900.31 2.450e0

到目前为止,我的代码如下所示。

import numpy as np
import os

myfiles = os.listdir('input')

for file in myfiles:
with open('input/'+file, 'r') as f:
data = np.loadtxt(f,delimiter='\t')


for row in data: ## remove data points where y is zero
data_filtered_both = data[data[:,1] != 0.000]
x_array=(data_filtered_both[:,0])
y_array=(data_filtered_both[:,1])
y_norm=(y_array/np.max(y_array))
x_and_y= np.array([list (i) for i in zip(x_array,y_array)])

precursor_x=[]
precursor_y=[]
for precursor in row: ## get data points where x is
precursor = x_and_y[:, np.abs(x_and_y[0,:]) > 520 and np.abs(x_and_y[0,:]) <1000]
precursor_x=np.array(precursor[0])
precursor_y=np.array(precursor[1])

我收到一条错误消息说......

  File "<ipython-input-45-0506fab0ad9a>", line 4, in <module>
precursor = x_and_y[:, np.abs(x_and_y[0,:]) > 2260 and np.abs(x_and_y[0,:]) <2290]

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

我该怎么办?我可以使用任何推荐的运营商吗?

P.S 我意识到 pandas dataframe 对于处理这样的数据集非常有用。我对 pandas 语言不是很熟悉,但如果有必要可以使用它。因此,我也将添加 pandas 作为我的标签。

最佳答案

您可以将 betweenboolean indexing 一起使用:

df = df[df['x'].between(520,1000)]
print (df)
x y
4 520.05 0.00
5 570.06 0.00
6 570.23 5.00
7 600.24 0.00
8 620.25 0.36
9 700.26 0.84
10 900.31 2.45

...并从 y 列中删除 0:

df = df[df['x'].between(520,1000) & (df['y'] != 0)]
print (df)
x y
6 570.23 5.00
8 620.25 0.36
9 700.26 0.84
10 900.31 2.45

query 评论为 2Obe :

df = df.query("x>500 & x<1000")
print (df)
x y
4 520.05 0.00
5 570.06 0.00
6 570.23 5.00
7 600.24 0.00
8 620.25 0.36
9 700.26 0.84
10 900.31 2.45

如果需要也过滤掉 y 列中的 0:

df = df.query("x>500 & x<1000 & y != 0")
print (df)
x y
6 570.23 5.00
8 620.25 0.36
9 700.26 0.84
10 900.31 2.45

关于python-3.x - 使用 python(或 pandas dataframe)在某个 x 范围内切片数据的一部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45699599/

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