pandas数据帧索引过滤

时间:2015-03-25 08:56:00

标签: python indexing pandas filter

我有两个相同时间分辨率的数据帧。从第一个数据帧(在我的例子中:df_data1)我只想要所有值['A'],其中['B']是< 90.现在我想过滤我的第二个数据帧,这样我只有第一个数据帧中具有相同时间戳(timeindex)的值

df_data1 = pd.io.parsers.read_csv(station_path, skiprows=0, index_col=0, na_values=[-999], names= names_header , sep=';', header=None , squeeze=True)

date     A  B
16.08.2013 03:00     -1  97
16.08.2013 03:15     -1  95
16.08.2013 03:30     0   92
16.08.2013 03:45     4  90
16.08.2013 04:00     18 88
16.08.2013 04:15     42 86
16.08.2013 04:30 73 83
16.08.2013 04:45     110    81
16.08.2013 05:00    151 78

现在我想要所有df_data ['A'],其中df_data ['B']是< 90。 所以我这样做:

df_data = df_data[(df_data['B']  < 90)]

第二个数据框如下所示:

df_data2 = pd.io.parsers.read_csv(station_path, skiprows=1, sep=";",  index_col=False, header=None)

date    w   x   y   z
16.08.2013 03:00    0   0   0   0
16.08.2013 03:15    0   0   0   0
16.08.2013 03:30    0   0   0   0
16.08.2013 03:45    0   0   0   0
16.08.2013 04:00    0   0   0   0
16.08.2013 04:15    0   0   0   0
16.08.2013 04:30    47  47  48  0
16.08.2013 04:45    77  78  79  88
16.08.2013 05:00    111 112 113 125

有人有想法解决这个问题吗? 我需要相同形状的数据帧,因此我还想计算np.corrcoef等等。

2 个答案:

答案 0 :(得分:2)

嗯,你的第一部分已经完成了:

df_data = df_data[(df_data['B']  < 90)]

然后,您可以使用df_data['A']

访问A列

如果您的索引值在两个df中都相同,那么这应该有效:

In [40]:

df1.loc[df_data.index]
Out[40]:
                       w    x    y   z
date                                  
2013-08-16 04:00:00    0    0    0   0
2013-08-16 04:15:00    0    0    0   0
2013-08-16 04:30:00   47   47   48   0
2013-08-16 04:45:00   77   78   79  88
2013-08-16 05:00:00  111  112  125 NaN

修改

不清楚为什么会得到KeyError,但您也可以使用以下内容:

df_data2[df_data2.index.isin(df_data1.index)]

这将处理第二个df中不存在的任何索引值。

答案 1 :(得分:1)

完成此操作:

  • 第一种方法我收到了错误

但是使用以下表达式可以很好地运行:

df_data2 [df_data2.index.isin(df_data1.index)]