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

问题描述 投票:0回答:4

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

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

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

需要任何帮助,在此先感谢。

pandas dataframe resampling
4个回答
0
投票

您可以做:

close_columns = [column for column in resamp.columns.to_flat_index() 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]

0
投票

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

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

或者,没有IndexSlice类,它看起来像这样:

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

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

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

0
投票

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

DataFrame.xs

如果需要避免df = df.xs('close', axis=1, level=1) ,则可以展平列名:

MultiIndex

0
投票

用途:

df.columns = df.columns.map('_'.join)
© www.soinside.com 2019 - 2024. All rights reserved.