Python示例函数TypeError:'str'和'int'的实例之间不支持'<'

数据挖掘 Python
2022-03-03 20:35:54

我在对示例数据帧代码进行抽样分层时遇到此错误,如下所示:

df = pd.DataFrame(dict(
    A=['a', 'a', 'a', 'b', 'c', 'c', 'c', 'a', 'b', 'b', 'b', 'c', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c'],
    B=range(20)


 ))


df.sample(n=100, weights='A',replace=True)

它给了我这个错误:

TypeError:“str”和“int”的实例之间不支持“<”

有人可以帮忙吗?

1个回答

欢迎来到本站!

我已经检查了这个问题,这是因为您正在尝试使用 str 变量创建样本。(df['A']). df.sample无法通过为分类变量分配权重来创建样本。

我做了一个小工作,即

df = pd.DataFrame(dict( A=['a', 'a', 'a', 'b', 'c', 'c', 'c', 'a', 'b', 'b', 'b', 'c', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c'], B=range(20) ))

#converting the text into categorical codes which are in numeric
df['cat'] = df.A.astype('category').cat.codes

#creating a sample using newly created column
Output = df.sample(n=100,weights = 'cat',replace=True)

输出将有 100 条记录,并使用“cat”作为权重创建。