重新排列 CSV 列

Ric*_*ich 0 python csv python-3.x python-3.6

创建 CSV 文件时,列不在我想要的正确位置。例如,“Period”列(变量是“RD”)是文件中的第二列等等。

有没有办法将每列的位置设置到我想要的位置?

我的代码:

from datetime import datetime
from elasticsearch import Elasticsearch
import csv

es = Elasticsearch(["9200"])


res = es.search(index="search", body=
                {
                    "_source": ["VT","NCR","N","DT","RD"],
                    "query": {

                        "bool": {
                            "must": [{"range": {"VT": {
                                            "gte": "now/d",
                                            "lte": "now+1d/d"}}},

                                {"wildcard": {"user": "mike*"}}]}}},size=10)


csv_file = 'File_' + str(datetime.now().strftime('%Y_%m_%d - %H.%M.%S')) + '.csv'


header_names = { 'VT': 'Date', 'NCR': 'ExTime', 'N': 'Name', 'DT': 'Party', ' RD ': 'Period'}



with open(csv_file, 'w', newline='') as f:
    header_present  = False
    for doc in res['hits']['hits']:
        my_dict = doc['_source']
        if not header_present:
            w = csv.DictWriter(f, my_dict.keys())
            w.writerow(header_names,) 
            header_present = True
             w.writerow(my_dict)
Run Code Online (Sandbox Code Playgroud)

小智 5

使用熊猫非常简单:

import pandas as pd


# Read csv / tab-delimited in this example
df = pd.read_csv('example.csv', sep='\t')

print df

   A  B  C
0  4  5  9
1  4  5  9
2  4  5  9
3  4  5  9

# Reorder columns
df = df[['C', 'A', 'B']]

print df

   C  A  B
0  9  4  5
1  9  4  5
2  9  4  5
3  9  4  5

# Write csv / tab-delimited
df.to_csv('example.csv', sep='\t')
Run Code Online (Sandbox Code Playgroud)