从没有列标题的 .csv 文件中删除整列 - 简单问题

Removing entire column from .csv file without column titles - simple question

我只想从 .csv 文件中完全删除第 6 至 11 列。不幸的是,实施在线找到的解决方案并没有获得任何修复。大多数解决方案删除。由列标题标识的列,但是,我的 .csv 文件没有列标题,因为将来没有它们会更容易。

from binance.client import Client
import config, csv
import pandas as pd

client = Client(config.apikey, config.apisecret)

candles = client.get_klines(symbol='ETHUSDT', interval=Client.KLINE_INTERVAL_1HOUR)

csvfile = open('1hour_dec2020_2021.csv', 'w', newline='')

candlestick_writer = csv.writer(csvfile, delimiter=',')


candlesticks=client.get_historical_klines('ETHUSDT', client.KLINE_INTERVAL_1HOUR, "1 Dec 2020", "1 Jan 2021")

for candlestick in candlesticks:
    candlestick_writer.writerow(candlestick)

csvfile.close()

.csv 文件中的示例行: 1502942400000,301.13000000,302.57000000,298.00000000,301.61000000,125.66877000,1502945999999,37684.80418100,129,80.56377000,24193.44078900,47039.70675719 对应币安kline响应

删除不需要的列最好会导致:- 时间戳、o、h、l、c、v 1502942400000,301.13000000,302.57000000,298.00000000,301.61000000,125.66877000

您可以使用 itemgetter() 从每一行中选择所需的值。在您的情况下,它们是连续的,因此您也可以使用一个简单的切片:

from operator import itemgetter
from binance.client import Client
import config, csv

required_cols = itemgetter(0, 1, 2, 3, 4, 5)        # specify required columns 
client = Client(config.apikey, config.apisecret)

with open('1hour_dec2020_2021.csv', 'w', newline='') as csvfile:
    candlestick_writer = csv.writer(csvfile)
    candlesticks = client.get_historical_klines('ETHUSDT', client.KLINE_INTERVAL_1HOUR, "1 Dec 2020", "1 Jan 2021")

    for candlestick in candlesticks:
        candlestick_writer.writerow(required_cols(candlestick))
        
        # or just use a slice if contiguous
        # csv_output.writerow(candlestick[:6])        

使用 with() 避免了添加 close()

的需要