python - 如何解决此“TypeError:序列项 0:预期的 str 实例,找到浮点数”
问题描述
我正在尝试使用 groupby 方法组合数据框列中的单元格值(字符串),使用逗号分隔分组单元格中的单元格值。我遇到了以下错误:
TypeError: sequence item 0: expected str instance, float found
错误发生在以下代码行,完整代码见代码块:
toronto_df['Neighbourhood'] = toronto_df.groupby(['Postcode','Borough'])['Neighbourhood'].agg(lambda x: ','.join(x))
似乎在groupby函数中,未分组数据框中每一行对应的索引在加入之前自动添加到字符串中。这会导致 TypeError。但是,我不知道如何解决这个问题。我浏览了很多线程,但没有找到解决方案。我将不胜感激任何指导或帮助!
# Import Necessary Libraries
import numpy as np
import pandas as pd
from bs4 import BeautifulSoup
import requests
# Use BeautifulSoup to scrap information in the table from the Wikipedia page, and set up the dataframe containing all the information in the table
wiki_html = requests.get('https://en.wikipedia.org/wiki/List_of_postal_codes_of_Canada:_M').text
soup = BeautifulSoup(wiki_html, 'lxml')
# print(soup.prettify())
table = soup.find('table', class_='wikitable sortable')
table_columns = []
for th_txt in table.tbody.findAll('th'):
table_columns.append(th_txt.text.rstrip('\n'))
toronto_df = pd.DataFrame(columns=table_columns)
for row in table.tbody.findAll('tr')[1:]:
row_data = []
for td_txt in row.findAll('td'):
row_data.append(td_txt.text.rstrip('\n'))
toronto_df = toronto_df.append({table_columns[0]: row_data[0],
table_columns[1]: row_data[1],
table_columns[2]: row_data[2]}, ignore_index=True)
toronto_df.head()
# Remove cells with a borough that is Not assigned
toronto_df.replace('Not assigned',np.nan, inplace=True)
toronto_df = toronto_df[toronto_df['Borough'].notnull()]
toronto_df.reset_index(drop=True, inplace=True)
toronto_df.head()
# If a cell has a borough but a Not assigned neighborhood, then the neighborhood will be the same as the borough
toronto_df['Neighbourhood'] = toronto_df.groupby(['Postcode','Borough'])['Neighbourhood'].agg(lambda x: ','.join(x))
toronto_df.drop_duplicates(inplace=True)
toronto_df.head()
'Neighbourhood' 列的预期结果应该使用逗号分隔分组单元格中的单元格值,显示如下(我还不能发布图像,所以我只提供链接):
解决方案
如评论中所述, theNaN
是一个浮点数,因此尝试对其进行字符串操作不起作用(这就是错误消息的原因)
用以下代码替换您的最后一部分代码:根据您在评论中指定的逻辑,使用布尔索引完成 nan 的填充
# If a cell has a borough but a Not assigned neighborhood, then the neighborhood will be the same as the borough
toronto_df.Neighbourhood = np.where(toronto_df.Neighbourhood.isnull(),toronto_df.Borough,toronto_df.Neighbourhood)
toronto_df['Neighbourhood'] = toronto_df.groupby(['Postcode','Borough'])['Neighbourhood'].agg(lambda x: ','.join(x))
推荐阅读
- reactjs - TypeScript 和 React JS 访问 DOM 元素
- .net - 从 .net 客户端订阅 IBM MQ 主题
- c# - 如何获取有关找到该术语的字段的信息
- r - 将 na.rm 作为参数添加到 r 中的自定义函数
- javascript - 文本对齐 froalaEditor
- image - Github Markdown 中的图片缩略图
- java - 如何设置通知的标题和内容?
- python - 两个 CNN 模型输出的组合
- sql - SQL 中的 ORDER BY 和 TOP 语句在列出记录时的工作方式不同,为什么?
- python - 添加新消息类型时此标记的值不正确(超出范围)