Python 在转换为dataframe时,保留Scrapy found字典的排序

Python 在转换为dataframe时,保留Scrapy found字典的排序,python,pandas,Python,Pandas,在抓取之后,我得到了一个字典列表,我将其转换为dataframe,然后对其进行一些计算。找到的字典顺序正确,但当我将它们转换为df时,它们就失去了顺序,变成了字母顺序。这是我的密码: import scrapy from openpyxl import Workbook import matplotlib.pyplot as plt import pandas as pd from PIL import Image import numpy as np #spider here process

在抓取之后,我得到了一个字典列表,我将其转换为dataframe,然后对其进行一些计算。找到的字典顺序正确,但当我将它们转换为df时,它们就失去了顺序,变成了字母顺序。这是我的密码:

import scrapy
from openpyxl import Workbook
import matplotlib.pyplot as plt
import pandas as pd
from PIL import Image
import numpy as np
#spider here
process = CrawlerProcess()
process.crawl(PythonEventsSpider)
spider = next(iter(process.crawlers)).spider
process.start()
# the order of dictionary is ['Name', 'Price', 'Link', 'Rating', 'Number of views',  'Price 1',
    #'Price 2', 'Price 3', 'Price 4', 'Fee', 'Price After Fee',
     #'Profit', 'Profit Percentage', 'Product ,'Notes']

df = pd.DataFrame(spider.found_items)
df.to_excel("{}.xlsx".format(file_name),sheet_name='All Products') # gets written in alphabetical order
#rest of code...

我检查了这个问题,但它是Python2,其中一些排序技术被贬低了

分配一个键列表,然后您可以使用以下命令从数据帧中选择所需的列:

keys = ['Name', 'Price', 'Link', 'Rating', 'Number of views', 'Price 1', 'Price 2', 'Price 3', 'Price 4', 'Fee', 'Price After Fee', 'Profit', 'Profit Percentage', 'Product' , 'Notes']

df = pd.DataFrame(spider.found_items)[keys]
df.to_excel("{}.xlsx".format(file_name), sheet_name='All Products')

分配一个键列表,然后可以按所需顺序使用以下键从数据帧中选择列:

keys = ['Name', 'Price', 'Link', 'Rating', 'Number of views', 'Price 1', 'Price 2', 'Price 3', 'Price 4', 'Fee', 'Price After Fee', 'Profit', 'Profit Percentage', 'Product' , 'Notes']

df = pd.DataFrame(spider.found_items)[keys]
df.to_excel("{}.xlsx".format(file_name), sheet_name='All Products')

像这样
df.sort(csv\u列,升序=[True for i in range(len(csv\u列))],inplace=True)
更好看,我现在测试我更新了我的答案,我最初错误地阅读了你的问题。我以为你想对数据进行排序,但是列的顺序不对。对不起!我知道我更新了我的答案,但要评论你的评论,
[True]*len(df.keys())
甚至更干净。像这样
df.sort(csv_列,升序=[True for I in range(len(csv_列))],inplace=True)
看起来更好,我现在会测试我更新了我的答案,我最初读错了你的问题。我以为你想对数据进行排序,但是列的顺序不对。对不起!我知道我更新了我的答案,但要评论你的评论,
[True]*len(df.keys())
更干净。