GUEST0 pt
クイズ・バイオインフォの森
8. 【python】様々なメソッド【pandas】

8. 【python】様々なメソッド【pandas】

目次

1. リスト・辞書などへの変換

to_list()

Text
# statistics
compounds = df_compounds.inchi_key.drop_duplicates().tolist()
compounds_proteins = df_compounds.uniprot_id.drop_duplicates().tolist()
print(f'n_compounds: {len(compounds)}')
print(f'n_proteins: {len(compounds_proteins)}')

to_dict()

indexをkeyとして指定のカラムをvalueとする辞書の作成。

Text
df_unp_sym = pd.read_csv('id_conversion/uniprotID_to_symbols.csv', index_col=1)
unp_sym = df_unp_sym['uniprot_gn_symbol'].to_dict()

任意の列をkeyとして指定のカラムをvalueとする辞書の作成。

Text
# 自作関数
def to_dict(df, key_col, value_col, unique=True):
    key_col_list = df[key_col].tolist()
    key_col_unique_list = list(set(key_col_list))
    value_col_list = df[value_col].tolist()


    kv = {k:[] for k in key_col_unique_list}
    for k, v in zip(key_col_list, value_col_list):
        kv[k].append(v)


    if unique:
        kv = {k: list(set(kv[k])) for k in kv.keys()}


    return kv


# 使用例
inc_to_sym = to_dict(df_compounds, 'inchi_key', 'symbol', unique=True)

2. apply/map

apply for series.

Text
df_compounds['symbol'] = df_compounds['uniprot_id'].apply(
    lambda x: unp_sym[x] if x in unp_sym.keys() else np.nan
)

apply for dataframe.

Text
# 縦ベクトルに対して関数を適用


# 横ベクトルに対して関数を適用
df_cn['dist'] = df_cn.apply(lambda x: np.sqrt((x.iloc[0] - xy[j][0])**2 + (x.iloc[1] - xy[j][1])**2), axis=1)

map for dataframe. 任意の要素に対して関数を実行。

Text
df_log10 = df.map(lambda x: np.log10(x))

3. ソート

特定の列に関してソート。

Text
# 昇順
df_cn = df_cn.sort_values('dist')


# 降順


# inplace

複数の列を基準にソート。

広告を取得中...
8. 【python】様々なメソッド【pandas】 | バイオインフォの森