重采样数据帧后如何删除不需要的列

时间:2019-10-30 12:56:24

标签: pandas dataframe resampling

我用以下代码创建了一个数据框:

import pandas as pd
import numpy as np
Timestamp = pd.date_range('21/1/2019', periods=2500, freq='10S')
df = pd.DataFrame(dtype=float)
df['Timestamp'] = Timestamp
LTP = np.arange(100,2600,1)
lowest_sell = np.arange(121,1371,0.5)
highest_buy = np.arange(131,1381,0.5)
df['a-LTP'] = LTP
df['b-Lowest_Sell'] = lowest_sell
df['c-Highest_Buy'] = highest_buy

这是数据框的外观:

enter image description here

我使用以下命令对其进行了重新采样:

resamp = df.set_index('Timestamp').resample('1T').ohlc()

这是重新采样的数据帧的样子:

enter image description here

如果您注意到,则在重新采样的数据框中将更改列的名称。 我只想在重新采样后“关闭”价格栏。 这是列的列表: enter image description here

如何删除不需要的列?由于列名现在很复杂,因此我无法使用简单的列删除方法。

任何帮助都需要事先感谢。

3 个答案:

答案 0 :(得分:3)

您可以这样做:

close_columns = [column for column in resamp.columns if column[1] == 'close']

result = resamp[close_columns]
print(result)

输出

                    a-LTP b-Lowest_Sell c-Highest_Buy
                    close         close         close
Timestamp                                            
2019-01-21 00:00:00   105         123.5         133.5
2019-01-21 00:01:00   111         126.5         136.5
2019-01-21 00:02:00   117         129.5         139.5
2019-01-21 00:03:00   123         132.5         142.5
2019-01-21 00:04:00   129         135.5         145.5
...                   ...           ...           ...
2019-01-21 06:52:00  2577        1359.5        1369.5
2019-01-21 06:53:00  2583        1362.5        1372.5
2019-01-21 06:54:00  2589        1365.5        1375.5
2019-01-21 06:55:00  2595        1368.5        1378.5
2019-01-21 06:56:00  2599        1370.5        1380.5

[417 rows x 3 columns]

要重命名,您可以执行以下操作:

lookup = {'a-LTP': 'resampled_LTP', 'b-Lowest_Sell': 'resampled_lowest_sell', 'c-Highest_Buy': 'resampled_highest_buy'}
result.columns = [lookup.get(column[0]) for column in result.columns]
print(result.columns)

输出

Index(['resampled_LTP', 'resampled_lowest_sell', 'resampled_highest_buy'], dtype='object')

答案 1 :(得分:2)

您现在有了一个MultiIndex。这些仍然是专栏,只是要多处理一些回旋处。我推荐这样的东西:

idx = pd.IndexSlice
resamp = resamp.loc[:,idx[:,"close"]]

或者,没有IndexSlice类,您可以获得相同的结果,但是语法更混乱:

resamp = resamp.loc[:,(slice(None),"close")]

输出:

>> resamp.head()
                    a-LTP b-Lowest_Sell c-Highest_Buy
                    close         close         close
Timestamp
2019-01-21 00:00:00   105         123.5         133.5
2019-01-21 00:01:00   111         126.5         136.5
2019-01-21 00:02:00   117         129.5         139.5
2019-01-21 00:03:00   123         132.5         142.5
2019-01-21 00:04:00   129         135.5         145.5

在这一切之后,您仍将拥有一个MultiIndex(只有一个唯一的第二级条目)-要摆脱第二级,您可以这样做:

resamp.columns = resamp.columns.droplevel(-1)

答案 2 :(得分:2)

如果要选择close中最简单的列MultiIndex,请使用DataFrame.xs

df = df.xs('close', axis=1, level=1)

如果要避免使用MultiIndex,可以将列名称变平:

df.columns = df.columns.map('_'.join)