【问题标题】:pandas dataframe slicing produce different results熊猫数据框切片产生不同的结果
【发布时间】:2019-01-08 09:54:25
【问题描述】:

我正在尝试通过将数据帧切片传递给我的函数来对加速度计数据进行带通滤波器,但根据切片数据的方式,我得到了不同的结果

我尝试使用iloc 使用列名和索引,但结果不同,所以我不知道哪个结果是正确的结果

我的带通滤波器功能:

def butter_bandpass(lowcut, highcut, fs, order=6):
    nyq = 0.5 * fs
    low = lowcut / nyq
    high = highcut / nyq
    b, a = butter(order, [low, high], btype='band')
    return b, a


def butter_bandpass_filter(data, lowcut, highcut, fs):
    b, a = butter_bandpass(lowcut, highcut, fs, order=6)
    y = lfilter(b, a, data)
    return y

以下两种方式,我曾经将数据传递给函数: 第一种方法:使用tremor_0[['X']] as [[]] 切片作为列名

y=pd.DataFrame(data=butter_bandpass_filter(tremor_0[['X']],0.3,12,100),columns=['X'])

第二种方式: 使用tremor_0['X'] as [] 切片作为列名

y=pd.DataFrame(data=butter_bandpass_filter(tremor_0['X'],0.3,12,100),columns=['X'])

第一种方式的结果:

    X
0   -0.001962
1   -0.001962
2   -0.001948
3   -0.001903
4   -0.001874

第二种方式的结果:

    X
0   -0.001962
1   -0.019822
2   -0.095867
3   -0.298136
4   -0.675933

请注意,从第二行开始,值是不同的,那么哪种方式是正确的方式,为什么?

screenshot of my work

【问题讨论】:

  • 欢迎来到 SO。请提供minimal example to produce the error。请记住,社区成员是志愿者,需要一些时间(和努力才能理解)或不完整的问题会阻止人们回答。

标签: python python-3.x pandas python-2.7


【解决方案1】:

简答:使用tremor_0['X']。

长答案

首先tremor_0[['X']]和tremor_0['X']是不一样的。

假设你有一个数据框:

df = pd.DataFrame(np.ndarray((100, 10)), columns=['x_%i' % i for i in range(10)])
type(df[['x_0']])
# pandas.core.frame.DataFrame
type(df['x_0'])
# pandas.core.series.Series

更重要的是,它们有不同的形状

df[['x_0']].shape
# (100, 1)
df['x_0'].shape
# (100, )

其中scipy.signal.lfilter 的处理方式不同,因为它将过滤器应用于axis=-1。

轴:int,可选 沿其应用线性滤波器的输入数据数组的轴。过滤器沿该轴应用于每个子阵列。默认为 -1。

如果您将 lfilter 参数更改为 axis = 0,butter_bandpass_filter 将返回包含样本值的数组。但请记住,生成的数组将遵循输入的形状。

【讨论】:

  • 感谢您的回复,如果我想传递三列数据框怎么办?传递它会更好 tremor_0_filterd=pd.DataFrame(data=butter_bandpass_filter(tremor_0[['X','Y','Z']],0.3,12,100),columns=['X','Y',' Z'])?
  • @GhaythMahadin 比什么更好,如果我可以问的话?
【解决方案2】:

当您使用tremor_0[['X']] 时,您会返回一个数据框对象,它是一个数组。当您使用 tremor_0['X'] 时,您会得到一个可以轻松转换为列表的 Series 对象

如果您只是尝试从一维列中提取数据,请使用tremor_0['X'],但您应该根据数据验证什么结果是有意义的以及您想要实现的目标

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-08-11
    • 1970-01-01
    • 2017-02-22
    • 1970-01-01
    • 2021-12-30
    • 1970-01-01
    • 2023-01-26
    • 2015-08-27
    相关资源
    最近更新 更多