pandas 数据帧索引过滤

pandas dataframe indexing filtering

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

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 等等。

好了,你的第一部分差不多完成了:

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 中不存在的任何索引值。

完成这个:

  • 第一种方法出现错误

但使用以下表达式效果很好:

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