2017-01-24 64 views
0

您好,我已經遍歷多列,它的工作。但在所有的CSV文件中的列名是爲了像這樣:遍歷多列後依次獲取列

Output: id title content tags 

但是我的代碼輸出順序列:

Output : content id tags title 

我怎麼找回來的順序,所有的該CSV文件作爲

這裏是我下面的代碼:

import glob 
import os 
import pandas as pd 
pd.set_option("display.max_rows", 999) 
pd.set_option('max_colwidth',100) 
import numpy as np 
from IPython.display import display 
%matplotlib inline 

file_path = 'data/'      
all_files = glob.glob(os.path.join(file_path, "*.csv"))  

merging_csv_files = (pd.read_csv(f) for f in all_files) 
stack_exchange_data = pd.concat(merging_csv_files, ignore_index=True) 

print ("Data loaded succesfully!") 
print ("Stack Exchane Data has {} rows with {} columns each.".format(*stack_exchange_data.shape)) 

回答

1

選擇的一般方法在一個特定的順序與列的數據幀是簡單地創建所需的順序列表,然後通過該列表數據幀的像這樣的支架操作:

my_col_order = ['id', 'title', 'content', 'tags'] 

df[my_col_order] 

你也可能要檢查所有的數據幀確實具有相同的列順序。我不相信Pandas會對concat中的列名進行排序,除非至少有一個DataFrame具有不同的列順序。您可能想要打印出所有要連接的DataFrame的所有列名稱。

+0

哇那麼簡單!像魅力一樣工作!謝謝@Ted Petrou –