Python Tutorial:Pandasデータフレーム PartⅡ

その買うを、もっとハッピーに。|ハピタス

前回のPython Tutorial:PandasシリーズとPandasデータフレームの続きをこのサイトを参照してやる。今回はデータをプロットして視覚化する方法を学習する。

スポンサーリンク

Loading and writing data

Read csv into a dataframe with
pd.ead_csv()
pd.ead_csv()を使ってCSVファイルのデータをデータフレームに取り込む

pd.ead_csv() can load a local .csv file or the one from the specified URL.
pd.ead_csv()は、ローカルドライブに保存された物以外に、指定URLのCSVファイルも取り込める。

# jupyter magics
%matplotlib inline
%config IPCompleter.greedy=True

# multiple output
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"
import numpy as np
import pandas as pd
from pandas import Series, DataFrame

csv_df = pd.read_csv('https://raw.githubusercontent.com/mwaskom/seaborn-data/master/fmri.csv')
csv_df.head()
subject timepoint event region signal
0 s13 18 stim parietal -0.017552
1 s5 14 stim parietal -0.080883
2 s12 18 stim parietal -0.081033
3 s11 18 stim parietal -0.046134
4 s10 18 stim parietal -0.037970
csv_df.columns
Index(['subject', 'timepoint', 'event', 'region', 'signal'], dtype='object')
csv_df_subset10 = csv_df[:10]

Write dataframe into .csv, .txt, .pickle or .xls
データフレームを、.csv, .txt, .pickle、もしくは、.xlsに書き込む

csv_df_subset10.to_csv('./temp_fmri_subset10.csv')
# csv_df_subset10.to_csv('./temp_fmri_subset10.txt')
# csv_df_subset10.to_excel('./temp_fmri_subset10.xls')
# csv_df_subset10.to_pickle('./temp_fmri_subset10')
スポンサーリンク

Basic preprocessing and analysis

Show all data type in the dataframe:
データフレーム内の全てのデータ型を表示

csv_df.dtypes
subject       object
timepoint      int64
event         object
region        object
signal       float64
dtype: object

Display the columns in the data:
データの列を表示

csv_df.columns
Index(['subject', 'timepoint', 'event', 'region', 'signal'], dtype='object')

Find unique values in [‘subject’], [‘event’] and [‘region’]:
[‘subject’],[‘event’],[‘region’]の固有の値を探し出す。

csv_df['subject'].unique()
csv_df['event'].unique()
csv_df['region'].unique()
array(['s13', 's5', 's12', 's11', 's10', 's9', 's8', 's7', 's6', 's4',
       's3', 's2', 's1', 's0'], dtype=object)
array(['stim', 'cue'], dtype=object)
array(['parietal', 'frontal'], dtype=object)

Access data based on conditions in other columns:
各条件に基づいて他の列のデータにアクセスする。

csv_df['event'][csv_df['subject']=='s1'][::5] # subsample output every 5
13      stim
83      stim
138     stim
210     stim
284     stim
350     stim
420     stim
489     stim
574      cue
649      cue
720      cue
782      cue
853      cue
923      cue
979      cue
1058     cue
Name: event, dtype: object

Categorical values can easily ba mapped to dummy variables using .map().
カテゴリー値は、.map()を用いて簡単にダミー変数にマッピングできる。

You can also use .apply() and a custom-made function to define a transformation to apply to a column of a dataframe
データフレームの列に適用するための変換を定義するために、.apply()や自前の関数を使うことできる。

csv_df['event'] = csv_df['event'].map({'cue': 0, 'stim': 1})
csv_df['event'][::75] # subsample output every 75
0       1
75      1
150     1
225     1
300     1
375     1
450     1
525     1
600     0
675     0
750     0
825     0
900     0
975     0
1050    0
Name: event, dtype: int64

Subselect data and sort
データをサブセレクトしてソートする


1
2
3
4
5
6
Below we want to select all fmri signal data from subject == s1 during event == 1 (stim) in region == frontal.  
以下で、event == 1 (stim)の間、region == frontalのsubject == s1から全fMRI信号データを選択したい。
We will ouput the signal values together with the corresponding timepoint values.  
対応するtimepoint値と共に、信号値を出力する。
Finally we will sort the data by the timepoint value.  
最後に、timepoint値でデータをソートする。
csv_df[['timepoint', 'signal']][(csv_df['subject']=='s1') & (csv_df['event']==1) & (csv_df['region']=='frontal')].sort_values(by='timepoint')
timepoint signal
284 0 -0.046049
281 1 -0.060273
295 2 -0.037520
309 3 0.057598
323 4 0.202123
336 5 0.315860
350 6 0.321335
364 7 0.204943
378 8 0.036685
392 9 -0.092768
406 10 -0.143302
420 11 -0.133647
434 12 -0.093411
449 13 -0.052714
463 14 -0.021003
476 15 -0.005134
489 16 -0.002719
520 17 -0.015686
516 18 -0.035852

This output can be saved as a np.array and be processed further on separately:
この出力は、np.arrayとして保存でき、今後個別に処理することができる。

data0 = csv_df[['timepoint', 'signal']][(csv_df['subject']=='s1') & (csv_df['event']==1) & (csv_df['region']=='frontal')].sort_values(by='timepoint').values[:, 1]

Basic descriptive statistics about the dataframe can ba accessed by calling df.describe(). Only valid for numerical dtype columns
df.describe()を呼び出すことで、データフレームに関する基本的な記述統計にアクセスできるが、これは、数値dtype列に対してのみ有効である。

csv_df.describe()
timepoint event signal
count 1064.000000 1064.000000 1064.000000
mean 9.000000 0.500000 0.003540
std 5.479801 0.500235 0.093930
min 0.000000 0.000000 -0.255486
25% 4.000000 0.000000 -0.046070
50% 9.000000 0.500000 -0.013653
75% 14.000000 1.000000 0.024293
max 18.000000 1.000000 0.564985

Basic operations can be run on column data as well as the entire dataframe:
基礎演算は、全データフレーム同様、列データに対し実行することが可能だ。

csv_df.sum()

csv_df['signal'].mean()
csv_df['signal'].sum()

csv_df[['signal']][(csv_df['timepoint']==10) & (csv_df['event']==1) & (csv_df['region']=='frontal')].corr()
subject      s13s5s12s11s10s9s8s7s6s5s4s3s2s1s0s13s12s7s10s...
timepoint                                                 9576
event                                                      532
region       parietalparietalparietalparietalparietalpariet...
signal                                                 3.76631
dtype: object
0.0035397685640969675
3.7663137521991734
signal
signal 1.0
スポンサーリンク

Basic visualization

Histofram of data can be plotted using .hist():
.hist()を使えば、データのヒストグラムをプロットすることができる。

csv_df['signal'].hist();

Categorical data can be easily plotted using .value_counts() (it counts unique values). Below is a histogram over the subjects
(固有値を数える).value_counts()を使って、カテゴリー値を簡単に描画できる。以下は、サブジェクトに対するヒストグラムだ。

csv_df['subject'].value_counts().plot(kind='bar');
csv_df[['signal']][(csv_df['timepoint']==10) & (csv_df['event']==1) & (csv_df['region']=='frontal')].plot();
csv_df[['signal']][(csv_df['timepoint']==9) & (csv_df['event']==1) & (csv_df['region']=='frontal')].plot();
スポンサーリンク

Exercise (練習問題)

1. Find all data that belongs to [‘subject’] == s1
[‘subject’] == s1に属する全データを検出する。
csv_df[['timepoint','signal','event','region']][csv_df['subject']=='s1'].sort_values(by='timepoint')[::10]
timepoint signal event region
84 0 -0.064454 1 0
727 2 -0.052213 0 0
336 5 0.315860 1 1
966 7 -0.053825 0 1
1014 10 -0.097984 0 1
434 12 -0.093411 1 1
853 15 0.003238 0 0
27 17 -0.038021 1 0
2. Turn [‘region’] to a dummy variable
[‘region’]をダミー変数に変換する。

csv_df['region'] = csv_df['region'].map({'parietal': 0, 'frontal': 1})
csv_df['region'][::75]
0       0
75      0
150     0
225     0
300     1
375     1
450     1
525     1
600     1
675     0
750     0
825     0
900     0
975     1
1050    1
Name: region, dtype: int64
3. Plot mean of signal of all subjects over 18 time points, during stimulation of parietal region
頭頂部刺激の間、18のtimepointsに対する全被験者の平均信号値をプロットする。タイムポイント別の全被験者の信号平均値は以下のようになる。

import matplotlib.pyplot as plt
%matplotlib inline  
plt.rcParams['figure.figsize']=12,8
plt.rcParams["font.size"] = "17"

mean_signal=[]
timepoint=[]
for i in range(0,19):
    timepoint.append(i)
    a = csv_df[['signal']][(csv_df['timepoint']==i) & (csv_df['event']==1) & (csv_df['region']==1)].mean()
    mean_signal.append(a)

_ = plt.xlabel('timepoint', fontsize=18, color='Blue')
_ = plt.ylabel('mean signal', fontsize=18, color='Blue')
_ = plt.xlim(0,18)
_ = plt.xticks(list(range(0,19)),[str(i) for i in range(0,19)])
_ = plt.grid(which='major',color='gray',linestyle='-')
_ = plt.plot(timepoint,mean_signal)
plt.show()

被験者別全タイムポイントの信号の平均値は以下のようになる。

import matplotlib.pyplot as plt
%matplotlib inline  
plt.rcParams['figure.figsize']=12,8
plt.rcParams["font.size"] = "17"

from natsort import natsorted, ns
sub = natsorted(csv_df['subject'].unique(), key=lambda y: y.lower())

mean_signal=[]
subject=[]
for i in sub:
    subject.append(i)
    a = csv_df[['signal']][(csv_df['subject']==i) & (csv_df['event']==1) & (csv_df['region']==1)].mean()
    mean_signal.append(a)

_ = plt.xlabel('subject', fontsize=18, color='Blue')
_ = plt.ylabel('mean signal', fontsize=18, color='Blue')
_ = plt.plot(subject,mean_signal)
_ = plt.xticks(sub,[str(i) for i in sub])
_ = plt.xlim(sub[0],sub[-1])
_ = plt.grid(which='major',color='gray',linestyle='-')
plt.show()

タイムポイント18の被験者別の信号平均値は以下のようになる。

import matplotlib.pyplot as plt
%matplotlib inline  
plt.rcParams['figure.figsize']=12,8
plt.rcParams["font.size"] = "17"

from natsort import natsorted, ns
sub = natsorted(csv_df['subject'].unique(), key=lambda y: y.lower())

mean_signal=[]
subject=[]
for i in sub:
    subject.append(i)
    a = csv_df[['signal']][(csv_df['subject']==i) & (csv_df['event']==1) & (csv_df['region']==1) & (csv_df['timepoint']==18)].mean()
    mean_signal.append(a)

_ = plt.xlabel('subject', fontsize=18, color='Blue')
_ = plt.ylabel('mean signal', fontsize=18, color='Blue')
_ = plt.plot(subject,mean_signal)
_ = plt.xticks(sub,[str(i) for i in sub])
_ = plt.xlim(sub[0],sub[-1])
_ = plt.grid(which='major',color='gray',linestyle='-')
plt.show()
4. Find mean and std of signal over subjects for all timepoints during stimulation vs cue in frontal region
前頭部における刺激vsキューの、全タイムポイントに対する被験者の信号の平均値と標準偏差を検出する。刺激に対する被験者別の信号平均値と標準偏差は以下のようになる。

import numpy as np

mean_signal=[]
std_signal=[]
subject=[]
for i in sub:
    subject.append(i)
    a = csv_df[['signal']][(csv_df['subject']==i) & (csv_df['event']==1) & (csv_df['region']==1)].mean()[-1]
    b = csv_df[['signal']][(csv_df['subject']==i) & (csv_df['event']==1) & (csv_df['region']==1)].std()[-1]
    mean_signal.append(a)
    std_signal.append(b)

df1 = pd.DataFrame(np.reshape(mean_signal,(1, 14)),index=["mean"], columns=sub)
df2 = pd.DataFrame(np.reshape(std_signal,(1, 14)),index=["std"], columns=sub)
df1.append(df2)
s0 s1 s2 s3 s4 s5 s6 s7 s8 s9 s10 s11 s12 s13
mean -0.006226 0.020972 -0.004589 0.027002 0.032395 0.00599 0.023976 0.03061 -0.016152 -0.031804 0.019667 -0.020058 -0.000120 0.011800
std 0.042445 0.139415 0.067046 0.132751 0.182878 0.10377 0.118210 0.07142 0.065891 0.047965 0.037434 0.092765 0.062761 0.095733

キューに対する被験者別の信号平均値と標準偏差は以下のようになる。

mean_signal=[]
std_signal=[]
subject=[]
for i in sub:
    subject.append(i)
    a = csv_df[['signal']][(csv_df['subject']==i) & (csv_df['event']==0) & (csv_df['region']==1)].mean()[-1]
    b = csv_df[['signal']][(csv_df['subject']==i) & (csv_df['event']==0) & (csv_df['region']==1)].std()[-1]
    mean_signal.append(a)
    std_signal.append(b)

df1 = pd.DataFrame(np.reshape(mean_signal,(1, 14)),index=["mean"], columns=sub)
df2 = pd.DataFrame(np.reshape(std_signal,(1, 14)),index=["std"], columns=sub)
df1.append(df2)
s0 s1 s2 s3 s4 s5 s6 s7 s8 s9 s10 s11 s12 s13
mean 0.013769 -0.008762 -0.001531 -0.013808 -0.009566 -0.005286 -0.015647 -0.020208 0.006312 0.014341 -0.011770 0.008837 -0.003588 -0.010209
std 0.029121 0.071522 0.036010 0.050439 0.094818 0.022636 0.033118 0.021137 0.013447 0.019800 0.019123 0.048615 0.004328 0.038123

刺激vsキューは以下のようになる。

a=csv_df[['signal']][(csv_df['event']==0) & (csv_df['region']==1)].mean()[-1]
b=csv_df[['signal']][(csv_df['event']==0) & (csv_df['region']==1)].std()[-1]
c=csv_df[['signal']][(csv_df['event']==1) & (csv_df['region']==1)].mean()[-1]
d=csv_df[['signal']][(csv_df['event']==1) & (csv_df['region']==1)].std()[-1]
e = {'cue': [a, b], 'stim': [c, d]}
pd.DataFrame(data=e,index=["mean","std"])
cue stim
mean -0.004080 0.006676
std 0.043054 0.098245
5. Plot bars for means of signal over all time points during stimulation in parietal and frontal regions for subejct 5
被験者5に対する頭頂部と前頭部における刺激の全タイムポイントにおける信号の平均値を棒グラフ化する。頭頂部の信号の平均値は以下のようになる。

mean_signal=[]
timepoint=[]
for i in range(0,19):
    timepoint.append(i)
    a = csv_df[['signal']][(csv_df['subject']=='s5') & (csv_df['timepoint']==i) & (csv_df['event']==1) & (csv_df['region']==0)].mean()[-1]
    mean_signal.append(a)

_ = plt.xlabel('timepoint', fontsize=18, color='Blue')
_ = plt.ylabel('mean signal', fontsize=18, color='Blue')
_ = plt.xlim(0,18)
_ = plt.xticks(list(range(0,19)),[str(i) for i in range(0,19)])
_ = plt.bar(timepoint,mean_signal)
plt.show()

前頭部の信号の平均値は以下のようになる。

mean_signal=[]
timepoint=[]
for i in range(0,19):
    timepoint.append(i)
    a = csv_df[['signal']][(csv_df['subject']=='s5') & (csv_df['timepoint']==i) & (csv_df['event']==1) & (csv_df['region']==1)].mean()[-1]
    mean_signal.append(a)

_ = plt.xlabel('timepoint', fontsize=18, color='Blue')
_ = plt.ylabel('mean signal', fontsize=18, color='Blue')
_ = plt.xlim(0,18)
_ = plt.xticks(list(range(0,19)),[str(i) for i in range(0,19)])
_ = plt.bar(timepoint,mean_signal)
plt.show()

頭頂部と前頭部の信号の平均値は以下のようになる。

mean_signal=[]
timepoint=[]
for i in range(0,19):
    timepoint.append(i)
    a = csv_df[['signal']][(csv_df['subject']=='s5') & (csv_df['timepoint']==i) & (csv_df['event']==1)].mean()[-1]
    mean_signal.append(a)

_ = plt.xlabel('timepoint', fontsize=18, color='Blue')
_ = plt.ylabel('mean signal', fontsize=18, color='Blue')
_ = plt.xlim(0,18)
_ = plt.xticks(list(range(0,19)),[str(i) for i in range(0,19)])
_ = plt.bar(timepoint,mean_signal)
plt.show()

頭頂部と前頭部の信号の平均値は以下の通り。

a=csv_df[['signal']][(csv_df['event']==1) & (csv_df['region']==0)].mean()[-1]
b=csv_df[['signal']][(csv_df['event']==1) & (csv_df['region']==1)].mean()[-1]
x = np.arange(2)
mean_signal=[a,b]
_ = plt.xlabel('region', fontsize=18, color='Blue')
_ = plt.ylabel('mean signal', fontsize=18, color='Blue')
_ = plt.bar(x, mean_signal)
_ = plt.xticks(x, ('parietal','frontal'))
plt.show()
スポンサーリンク
スポンサーリンク