我是Python.I的初学者,我将两个columnsAfter合并在一起,我尝试将列的‘未赋值’值更改为另一个列值。我不能那样做。如果我使用premodified dataframe,那么我可以更改。
我从页面中抓取了一个表,然后修改了数据中的数据。
import pandas as pd
import numpy as np
import requestspip安装lxml
toronto_url='https://en.wikipedia.org/wiki/List_of_postal_codes_of_Canada:_M'
toronto_df1= pd.read_html('https://en.wikipedia.org/wiki/List_of_postal_codes_of_Canada:_M')[0]
toronto_df1.head()
toronto_df1.drop(toronto_df1.loc[toronto_df1['Borough']=="Not assigned"].index, inplace=True)
toronto_df2=toronto_df1.groupby(['Postcode','Borough'],sort=False).agg(lambda x: ','.join(x))
toronto_df2.loc[toronto_df2['Neighbourhood'] == "Not assigned", 'Neighbourhood'] = toronto_df2['Borough']这是我用过的代码。
我希望用区长值来改变邻里值。
我犯了这个错误。
/usr/local/lib/python3.6/dist-packages/pandas/core/indexes/base.py in get_loc(自、键、方法、容限) 2656尝试:-> 2657返回self._engine.get_loc( key ) 2658 ( KeyError除外): pandas._libs.index.IndexEngine.get_loc()中的熊猫/_libs/index.pyx pandas._libs.index.IndexEngine.get_loc()中的熊猫/_libs/index.pyx pandas._libs.hashtable.PyObjectHashTable.get_item()中的熊猫/libs/hashtable_class_helper.pxi pandas._libs.hashtable.PyObjectHashTable.get_item()中的熊猫/libs/hashtable_class_helper.pxi KeyError:“区”
在处理上述异常的过程中,发生了另一个异常:
/usr/local/lib/python3.6/dist-packages/pandas/core/indexes/base.py (自,键,方法)中的9帧KeyError跟踪(最近一次调用)(公差) 2657返回self._engine.get_loc(键) 2658除KeyError:-> 2659返回KeyError 2660 indexer = self.get_indexer(key,method=method,tolerance=tolerance) 2661,如果indexer.ndim >1或indexer.size > 1: pandas._libs.index.IndexEngine.get_loc()中的熊猫/_libs/index.pyx pandas._libs.index.IndexEngine.get_loc()中的熊猫/_libs/index.pyx pandas._libs.hashtable.PyObjectHashTable.get_item()中的熊猫/libs/hashtable_class_helper.pxi pandas._libs.hashtable.PyObjectHashTable.get_item()中的熊猫/libs/hashtable_class_helper.pxi KeyError:“区”
发布于 2019-09-16 06:13:31
您的keyerror的原因不是Neighbourhood列,而是索引级别,解决方案是添加reset_index。
toronto_df1= pd.read_html('https://en.wikipedia.org/wiki/List_of_postal_codes_of_Canada:_M')[0]
#boolean indexing
toronto_df1 = toronto_df1.loc[toronto_df1['Borough']!="Not assigned"]
toronto_df2 = toronto_df1.groupby(['Postcode','Borough'],sort=False)['Neighbourhood'].agg(','.join).reset_index()
toronto_df2.loc[toronto_df2['Neighbourhood'] == "Not assigned", 'Neighbourhood'] = toronto_df2['Borough']或参数as_index=False到groupby
toronto_df1= pd.read_html('https://en.wikipedia.org/wiki/List_of_postal_codes_of_Canada:_M')[0]
#boolean indexing
toronto_df1 = toronto_df1.loc[toronto_df1['Borough']!="Not assigned"]
toronto_df2=toronto_df1.groupby(['Postcode','Borough'],sort=False, as_index=False)['Neighbourhood'].agg(','.join)
toronto_df2.loc[toronto_df2['Neighbourhood'] == "Not assigned", 'Neighbourhood'] = toronto_df2['Borough']https://stackoverflow.com/questions/57951186
复制相似问题