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

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


数据框如下所示:

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

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

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


重新采样的数据帧如下所示:

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

如果您注意到,列名将在重新采样的数据框中更改。
我只想在重新采样后“关闭”价格栏。
这是列的列表:
pandas - 重采样数据帧后如何删除不需要的列-LMLPHP

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

任何帮助都需要提前感谢。

最佳答案

您可以这样做:

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')

关于pandas - 重采样数据帧后如何删除不需要的列,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58625890/

10-12 23:53
查看更多