我正在尝试查找从PANDAS数据帧生成的timeDelta对象列表的中位数。我已经尝试过使用统计资料库:
newList= list(DF.sort_values(['TimeDelta'])['TimeDelta'])
TDmedian = (st.median(newList))
st是我导入统计库的方式。
但是我得到了错误:
`TypeError: unsupported operand type(s) for /: 'str' and 'int'`
我试图制作一个函数来计算它:`
def date_median(date_list):
length = len(date_list)
print(length)
//Checks if the length is odd cause median in odd numbered lists is the middle value
if length % 2 != 0:
return date_list[length//2]
else:
//If it's even, it'll take the middle value and the one above it and generate the mean
print((length//2), (length//2+1))
lower = date_list[length//2]
upper = date_list[(length//2) +1]
return (lower + upper)/2`
我像这样使用它:
`TAmedian = date_median(newList)`
我收到此错误:
`TypeError: unsupported operand type(s) for /: 'str' and 'int'`
是否有更简单的方法来执行此操作,如果没有,那么我在做什么错呢?
样本数据:
DF['TimeDelta'] = [0 days 00:00:36.35700000,0 days 00:47:11.213000000]
确定。它应该工作。著名的遗言吧?
我怀疑您的数据框的该列中有一些不是数字的元素。它的工作方式应与此类似:
In [17]: import pandas as pd
In [18]: tds = [timedelta(t) for t in range(5)]
In [19]: x = list(range(5))
In [20]: df = pd.DataFrame({'x': x, 'time delta': tds})
In [21]: df
Out[21]:
x time delta
0 0 0 days
1 1 1 days
2 2 2 days
3 3 3 days
4 4 4 days
In [22]: import numpy as np
In [23]: np.median(df['time delta'])
Out[23]: numpy.timedelta64(172800000000000,'ns')
所以,您是否测试了数据框以查看该列中是否有一些非数字值?最简单的就是使用info()
命令。它看起来应该与此相似。如果显示“对象”,则需要找出原因。
In [24]: df.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 5 entries, 0 to 4
Data columns (total 2 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 x 5 non-null int64
1 time delta 5 non-null timedelta64[ns]
dtypes: int64(1), timedelta64[ns](1)
memory usage: 208.0 bytes
In [25]: df.describe()
Out[25]:
x time delta
count 5.000000 5
mean 2.000000 2 days 00:00:00
std 1.581139 1 days 13:56:50.394919
min 0.000000 0 days 00:00:00
25% 1.000000 1 days 00:00:00
50% 2.000000 2 days 00:00:00
75% 3.000000 3 days 00:00:00
max 4.000000 4 days 00:00:00
这是有关寻找非数字值的好文章: