【问题标题】:python 2 vs python 3 columns ordering using pandaspython 2 vs python 3列使用pandas排序
【发布时间】:2018-07-24 00:29:53
【问题描述】:

我在将其保存为 csv 时遇到了与 pandas 数据框中的列排序相关的问题。这是 python 3 中的排序:

在 python 2 中,它会还原列,如果列数大于 2,则排序完全不同

这是我将数据框保存为 csv 的代码:

selective_price = []
for index_sample, row_sample in selectivePriceList.iterrows():
    selective_price.append(row_sample.loc[list_keys])
    counter +=1
    #print(selective_price)  
selective_price = pd.concat(selective_price, axis=1) 
selective_price = selective_price.transpose()
selective_price.insert(0, "Date", DateFrame.loc[index:index+(w-1)], allow_duplicates=False)
#print(selective_price)
start_end_date = str(DateFrame[index]) + "_" + str(DateFrame[index+(w-1)])
#print (start_end_date)
selective_price = selective_price.sort_values(by=['Date'])
print (selective_price.columns)
selective_price.to_csv('rolling_results_'+start_end_date+"_.csv",index=False)

使用 selective_price = selective_price.sort_index().transpose() 时,列按字母顺序排序,索引不正确

而正确的索引必须是

【问题讨论】:

  • print (selective_price.columns) 在 Python2 和 Python3 中打印出不同的结果吗?
  • Index([u'Date', u'litecoin', u'bitcoin'], dtype='object') python2 和 Index(['Date', 'bitcoin', 'litecoin'], dtype='object') python3
  • 我想这就解释了
  • 所以,希望我能解决这个问题
  • 您认为有什么帮助

标签: python python-3.x python-2.7 list pandas


【解决方案1】:

既然你在这里转置了DataFrame:

selective_price = selective_price.transpose()

原来的索引变成了新的列名,所以你可以简单地先排序:

selective_price = selective_price.sort_index().transpose()

现在无论 Python 版本如何,都会对列名进行排序。

可能首先发生这种情况的原因是您从没有排序的dict 加载数据。

【讨论】:

  • 如果超过 2 列,结果排序不正确,按字母顺序排序我已经编辑了关于这一点的问题
  • 如果你想要一个特定的顺序,那么在转置后用你想要的任何顺序执行selectice_price[['bitcoin', 'litecoin', ...]]
猜你喜欢
  • 2012-07-09
  • 2019-01-06
  • 1970-01-01
  • 2021-09-12
  • 2018-05-11
  • 2018-04-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多