Pandas忽略缺失的日期来寻找百分位数

2024-09-26 22:44:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数据帧。我在试着找出日期时间的百分位数。我正在使用函数:

数据帧:

student, attempts, time
student 1,14, 9/3/2019  12:32:32 AM
student 2,2, 9/3/2019  9:37:14 PM
student 3, 5
student 4, 16, 9/5/2019  8:58:14 PM

studentInfo2 = [14, 4, Timestamp('2019-09-04 00:26:36')]
data['time'] = pd.to_datetime(data['time_0001'], errors='coerce')
perc1_first = stats.percentileofscore(data['time'].notnull(), student2Info[2], 'rank')

其中student2Info[2]保存特定学生的日期时间。当我尝试这样做时,我得到了一个错误:

TypeError: ufunc 'isnan' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

有没有关于如何让百分位数正确计算的想法,即使列中缺少时间?你知道吗


Tags: theto数据函数datatime时间not
1条回答
网友
1楼 · 发布于 2024-09-26 22:44:17

您需要将时间戳转换成percentileofscore可以理解的单位。另外,pd.DataFrame.notnull()返回一个布尔列表,您可以使用它来过滤您的DataFrame,它不返回过滤后的列表,所以我为您更新了它。下面是一个工作示例:

import pandas as pd
import scipy.stats as stats

data = pd.DataFrame.from_dict({
    "student": [1, 2, 3, 4],
    "attempts": [14, 2, 5, 16],
    "time_0001": [
        "9/3/2019  12:32:32 AM",
        "9/3/2019  9:37:14 PM",
        "",
        "9/5/2019  8:58:14 PM"
    ]
})

student2Info = [14, 4, pd.Timestamp('2019-09-04 00:26:36')]
data['time'] = pd.to_datetime(data['time_0001'], errors='coerce')
perc1_first = stats.percentileofscore(data[data['time'].notnull()].time.transform(pd.Timestamp.toordinal), student2Info[2].toordinal(), 'rank')
print(perc1_first)  #-> 66.66666666666667

相关问题 更多 >

    热门问题