在pandas to_csv方法中保留列顺序 [英] Preserving column order in the pandas to_csv method
问题描述
pandas的to_csv方法不保留列的顺序.它选择按字母顺序排列CSV列.这是一个错误,已经得到报告,应该在版本0.11.0中得到纠正.我有0.18.0.
The to_csv method of pandas does not preserve the order of columns. It chooses to alphabetically arrange the columns in CSV. This is a bug and has been reported and is supposed to be corrected in version 0.11.0. I have 0.18.0.
import pandas as pd
df = pd.DataFrame({'V_pod_error' : [a],
'V_pod_used' : [b],
'U_sol_type' : [c]
...
... and so on upto 50 columns }
pd.to_csv(df)
Excel订单:
0 U_sol type V_pod_error V_pod_used ...
1
我想要的是在字典中的顺序:
What I want is order in the dictionary:
0 V_pod_error V_pod_used U_sol type ...
1
我有大量的列和名称.我无法手动执行或写出列顺序.在此处中,存在完全相同的问题.而且看起来好像没有更新!我想请社区帮助我!这真的有问题.
I have a huge number of columns and names. I cannot do it manually or write out the column order. There has been the exact same question in 2013 here. And it doesnt look like there is an update! I would like to ask the community to help me out! This is really problematic.
推荐答案
尝试以下解决方案.甚至我也面临同样的问题.我解决了如下问题:
Try the following solution. Even I faced the same issue. I solved it as follows:
import pandas as pd
df = pd.DataFrame({'V_pod_error' : [a],
'V_pod_used' : [b],
'U_sol_type' : [c]
...
... and so on upto 50 columns }
column_order = ['V_pod_error', 'V_pod_used', 'U_sol_type',.....# upto 50 column names]
df[column_order].to_csv(file_name)
这篇关于在pandas to_csv方法中保留列顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!