【发布时间】:2018-10-25 16:05:17
【问题描述】:
我有这个熊猫数据框,每行包含两个样本 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()(以两个样本作为输入的统计测试),并取响应的第一个元素(函数返回两个元素):
-
如果我对给定的行执行此操作,例如第一行,它有效:
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')
我做错了什么?
【问题讨论】:
标签: python python-3.x pandas scipy