[英]How to apply scipy function on Pandas data frame
我有以下數據框:
import pandas as pd
import io
from scipy import stats
temp=u"""probegenes,sample1,sample2,sample3
1415777_at Pnliprp1,20,0.00,11
1415805_at Clps,17,0.00,55
1415884_at Cela3b,47,0.00,100"""
df = pd.read_csv(io.StringIO(temp),index_col='probegenes')
df
看起來像這樣
sample1 sample2 sample3
probegenes
1415777_at Pnliprp1 20 0 11
1415805_at Clps 17 0 55
1415884_at Cela3b 47 0 100
我也想使用SCIPY執行row-zscore計算 。 使用此代碼,我得到:
In [98]: stats.zscore(df,axis=1)
Out[98]:
array([[ 1.18195176, -1.26346568, 0.08151391],
[-0.30444376, -1.04380717, 1.34825093],
[-0.04896043, -1.19953047, 1.2484909 ]])
如何方便地將列和索引名稱重新附加到該結果?
在一天結束時。 它看起來像:
sample1 sample2 sample3
probegenes
1415777_at Pnliprp1 1.18195176, -1.26346568, 0.08151391
1415805_at Clps -0.30444376, -1.04380717, 1.34825093
1415884_at Cela3b -0.04896043, -1.19953047, 1.2484909
pd.DataFrame
的文檔具有:
data :numpy ndarray(結構化或均質化),dict或DataFrame Dict可以包含Series,數組,常量或類似列表的對象index :用於生成結果幀的Index或類似array的Index。 如果沒有輸入數據的索引信息部分並且沒有提供索引,則默認為np.arange(n) 列 :用於結果幀的索引或類似數組的列標簽。 如果未提供列標簽,則默認為np.arange(n)
所以,
pd.DataFrame(
stats.zscore(df,axis=1),
index=df.index,
columns=df.columns)
應該做的工作。
你不需要臭味。 您可以使用lambda函數來做到這一點:
>>> df.apply(lambda row: (row - row.mean()) / row.std(ddof=0), axis=1)
sample1 sample2 sample3
probegenes
1415777_at Pnliprp1 1.181952 -1.263466 0.081514
1415805_at Clps -0.304444 -1.043807 1.348251
1415884_at Cela3b -0.048960 -1.199530 1.248491
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.