数据框fit_transform抛出错误,看似错误

时间:2018-11-08 03:21:15

标签: python python-3.x pandas dataframe

我正在Python中运行给定的行:

df = df.apply(lambda x: d[x.name].fit_transform(x))

并出现以下错误:

~/anaconda3/envs/python3/lib/python3.6/site-packages/numpy/lib/arraysetops.py in _unique1d(ar, return_index, return_inverse, return_counts)
278 
279     if optional_indices:
--> 280         perm = ar.argsort(kind='mergesort' if return_index else 'quicksort')
281         aux = ar[perm]
282     else:

TypeError: ("'<' not supported between instances of 'str' and 'float'", 'occurred at index name')

文件中的任何地方都没有字符“ <”,所以不确定错误是什么吗?

Python的新手,因此对如何理解这些错误的任何见解都将受到赞赏。

1 个答案:

答案 0 :(得分:0)

我认为这可能是因为您没有向您的fit_transform发送干净或正确的数据。在评论中不回答我的问题就很难说(ddf = df.apply(lambda x: d[x.name].fit_transform(x))中代表什么?)

我获取了一些虚拟数据,并举例说明了如何使用apply将fit_transform应用于数据框。

import random
import pandas as pd
import numpy as np

# Random dummy data
s = "Crime Type Summer|Crime Type Winter".split("|")
j = {x: [random.choice(["ASB", "Violence", "Theft", "Public Order", "Drugs"]) for j in range(300)] for x in s}
df = pd.DataFrame(j)

# Instantiate the vectorizer for use in the lambda function.
from sklearn.feature_extraction.text import CountVectorizer
cv = CountVectorizer()

# Now we can call the transform directly in the lambda function.
df = df.apply(lambda x: cv.fit_transform(df[x.name].values))

此操作成功完成并给出:

Crime Type Summer      (0, 1)\t1\n  (1, 4)\t1\n  (2, 2)\t1\n  (2, 3...
Crime Type Winter      (0, 5)\t1\n  (1, 0)\t1\n  (2, 0)\t1\n  (3, 5...
dtype: object