簡體   English   中英

函數適用於數據幀的每一行,但不使用df.apply

[英]Function works on each row of data frame, but not using df.apply

我有這個pandas數據幀,每行包含兩個樣本X和Y:

import pandas as pd
import numpy as np
df = pd.DataFrame({'X': [np.random.normal(0, 1, 10),
                         np.random.normal(0, 1, 10),
                         np.random.normal(0, 1, 10)],
                   'Y': [np.random.normal(0, 1, 10),
                         np.random.normal(0, 1, 10),
                         np.random.normal(0, 1, 10)]})

我想在每一行上使用函數ttest_ind() (以兩個樣本作為輸入的統計測試),並獲取響應的第一個元素(該函數返回兩個元素):

  • 如果我為給定的行(例如第1行)執行此操作,則可以:

     from scipy import stats stats.ttest_ind(df['X'][0], df['Y'][0], equal_var = False)[0] # Returns a float 
  • 但是,如果我使用apply在每一行上執行它,我會收到一個錯誤:

     df.apply(lambda x: stats.ttest_ind(x['X'], x['Y'], equal_var = False)[0]) # Throws the following error: Traceback (most recent call last): File "pandas\\_libs\\index.pyx", line 154, in pandas._libs.index.IndexEngine.get_loc File "pandas\\_libs\\hashtable_class_helper.pxi", line 759, in pandas._libs.hashtable.Int64HashTable.get_item TypeError: an integer is required During handling of the above exception, another exception occurred: ... KeyError: ('X', 'occurred at index X') 

我究竟做錯了什么?

您只需指定要應用函數的軸。 查看apply()的相關文檔 簡而言之, axis = 1表示“將函數應用於我的數據幀的每一行”。 默認值為axis = 0 ,它嘗試將函數應用於每列。

df.apply(lambda x: stats.ttest_ind(x['X'], x['Y'], equal_var = False)[0], axis=1)

0    0.985997
1   -0.197396
2    0.034277

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM