2017-06-18 24 views
1

我正在嘗試繪製來自多個數據幀的年齡列的直方圖分佈。 以下是我嘗試的一段代碼,但它給出了空白的情節。將多個數據幀的連續時間列合併爲一個並繪製直方圖

import pandas as pd 
import glob 
import matplotlib.pyplot as plt 
%matplotlib inline 

filelist = glob.glob('/Users/kadb/Desktop/participants_tsv_files/*.tsv') 
# fig = plt.figure() 
ax = fig.add_subplot(111) 
# ax.xaxis.set_ticks(df.index) 
# ax.xaxis.set_ticklabels(df['g']) 
plt.figure() 
for file in filelist: 
    df = pd.read_table(file) 
    if 'age' in df.columns: 
     df = df[~df["age"].isin(["n/a"])] # remove n/a values 
     result = result.append(df,ignore_index=True) 
     result = pd.concat([df,result], axis=1) 
     plt.hist(result, normed=1, facecolor='green') 

例如TSV文件:

participant_id gender age physioSampling restAcquisiotion 
sub-01 M 26 50 after_cuedSGT 
sub-02 M 21 50 after_cuedSGT 
sub-03 M 22 50 after_cuedSGT 
sub-04 M 23 N/A after_cuedSGT 
sub-05 M 21 50 before_cuedSGT 
sub-06 M 19 n/a before_cuedSGT 
sub-07 F 18 50 before_cuedSGT 
sub-08 F 21 50 before_cuedSGT 
sub-09 M 20 40-60 before_cuedSGT 
sub-10 F 21 50 before_cuedSGT 
sub-11 F 20 50 before_cuedSGT 
sub-12 M 21 50 before_cuedSGT 
sub-13 F 31 50-60 before_cuedSGT 
+0

我想你想'軸= 0'在'pd.concat '聲明,因爲您試圖向單個「年齡」列添加更多行,而不是創建多個「年齡」列。另外,我猜你只是想在最後右邊畫一次?如果是這樣,'plt.hist'不應該在'for'循環中縮進。 –

+0

要繪製多個直方圖還是隻繪製1個(適用於所有表格中的所有年齡段)? –

+0

嘗試在循環之前初始化結果列表(即'results = []')。在所有的'df'被追加到結果列表中,但只把'pandas.concat'放到循環中。 – CiaranWelsh

回答

0

我有一個想法:1)收集所有dataframes ages; 2)地塊直方圖

介紹

import pandas as pd 
import glob 
import matplotlib.pyplot as plt 
%matplotlib inline 
filelist = glob.glob('/Users/kadb/Desktop/participants_tsv_files/*.tsv') 

收集HIST年齡

ages = [] 
for file in filelist: 
    df = pd.read_table(file) 
    if 'age' in df.columns: 
     df = df[~df["age"].isin(["n/a"])] # remove n/a values 
     ages.extend(df.age.values) 

情節HIST

fig = plt.figure(figsize = (7,7)) 
plt.grid(True) 
plt.xlabel("age") 
plt.xlabel("density") 
plt.hist(ages, normed=1, facecolor='green') 
plt.show() 
相關問題