2015-11-09 84 views
0

我想從使用Python的熊貓模塊的csv文件中提取數據。實驗數據有6列(可以說a,b,c,d,e,f),我有一個模型目錄列表。不是每個模型都有6個'物種'(列),所以我需要專門爲每個模型分割數據。這裏是我的代碼:使用蟒蛇熊貓收集數據循環數據框

def read_experimental_data(self,experiment_path): 
     [path,fle]=os.path.split(experiment_path) 
     os.chdir(path) 
     data_df=pandas.read_csv(experiment_path) 
#  print data_df 
     experiment_species=data_df.keys() #(a,b,c,d,e,f) 
#  print experiment_species 
     for i in self.all_models_dirs: #iterate through a list of model directories. 
      [path,fle]=os.path.split(i) 
      model_specific_data=pandas.DataFrame() 
      species_dct=self.get_model_species(i+'.xml') #gives all the species (culuns) in this particular model 
#   print species_dct 
      #gives me only species that are included in model dir i 
      for l in species_dct.keys(): 
       for m in experiment_species: 
        if l == m: 
         #how do i collate these pandas series into a single dataframe? 
         print data_df[m] 

上面的代碼給了我正確的數據,但我有麻煩收集它在一個可用的格式。我試圖合併和連接它們,但沒有喜悅。有人知道怎麼做這個嗎?

感謝

回答

1

你可以通過它,你要列清單創建data_df一個新的數據幀,

import pandas as pd 
df = pd.DataFrame({'a': [1,2,3], 'b': [4,5,6], 'c': [7,8,9]}) 
df_filtered = df[['a', 'c']] 

或使用你的一些變量名的例子,

import pandas as pd 
data_df = pd.DataFrame({'a': [1,2], 'b': [3,4], 'c': [5,6], 
        'd': [7,8], 'e': [9,10], 'f': [11,12]}) 
experiment_species = data_df.keys() 
species_dct = ['b', 'd', 'e', 'x', 'y', 'z'] 
good_columns = list(set(experiment_species).intersection(species_dct)) 
df_filtered = data_df[good_columns]