python - Python Pandas ValueError : Series 的真值不明确
问题描述
即使这是一个重复的问题,我在下面找不到我的问题的确切解决方案..
我有一个名为“data1”的熊猫数据框,我想获取数据类型为“对象”的列的唯一类别数。下面是我使用的代码
for col in data1.columns:
if data1[col].dtypes =='object':
unique_category = len(data1[col].unique())
print("feature '{col}' has '{unique_category}' unique catogories".format(col=col,unique_category=unique_category))
此代码在其他程序中运行良好。但这次它给出了以下错误
V
alueError Traceback (most recent call last)
<ipython-input-178-03999268fffa> in <module>()
1 for col in data1.columns:
----> 2 if data1[col].dtypes =='object':
3 unique_category = len(data1[col].unique())
4 print("feature '{col}' has '{unique_category}' unique catogories".format(col=col,unique_category=unique_category))
5
~\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\generic.py in __nonzero__(self)
1571 raise ValueError("The truth value of a {0} is ambiguous. "
1572 "Use a.empty, a.bool(), a.item(), a.any() or a.all()."
-> 1573 .format(self.__class__.__name__))
1574
1575 __bool__ = __nonzero__
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
有什么理由给出错误信息吗?
解决方案
这是一个例子:
# Create data set
d = {'foo':[100, 111, 222],
'bar':['333', '444', '555']}
df = pd.DataFrame(d)
df
# bar foo
# 0 333 100
# 1 444 111
# 2 555 222
df.info()
# <class 'pandas.core.frame.DataFrame'>
# RangeIndex: 3 entries, 0 to 2
# Data columns (total 2 columns):
# bar 3 non-null object # <- object type column
# foo 3 non-null int64
# dtypes: int64(1), object(1)
# memory usage: 128.0+ bytes
for col in range(len(df.dtypes)):
if df.dtypes[col] == 'O': # <- can also use `O`
unique_category = len(df.loc[:,df.columns[col]].unique())
print("feature '{col}' has '{unique_category}' unique categories".format(col=df.columns[col],unique_category=unique_category))
# feature 'bar' has '3' unique categories
推荐阅读
- curl - 从 Netsuite Rest API 获取格式错误的输出
- r - 基于另一个变量的变量的汇总统计
- ssl-certificate - 在多个进程之间共享临时客户端证书存储
- html - React useState 钩子附加到输入类型号而不更新鼠标滚动时的值
- c# - C# WebClient 从站点获取 html 时收到 403
- javascript - 如何在 django 的输入标签中显示数据库中的值?
- java - Wildfly 中的自签名证书不起作用,但适用于 spring-boot
- docusignapi - QuickStart 应用程序出错 - 重定向 URI 未在 DocuSign 中正确注册
- react-native - 使用 npm 安装 react-navigation 会出错
- html - Outlook 预览功能通过 HTML 代码错误地显示符号