英文:
Mapping States to zipcodes in pandas dataframe
问题
我有一个经过清理的pandas数据帧,只包含一个邮政编码列,我试图使用pyzipcode在执行时返回相应的州名到一个新列中:
```python
from pyzipcode import ZipCodeDatabase
import pandas as pd
import os
zcdb = ZipCodeDatabase()
df = pd.read_excel(r'G:\Downloads\testzip.xlsx')
df[pd.to_numeric(df['Zip'], errors='coerce').notnull()]
df = df.dropna
df['state'] = df['Zip'].map(lambda x: zcdb[x].state)
不幸的是,我收到了以下错误:
'method' object is not subscriptable
不知道为什么。有人知道这里发生了什么吗?
<details>
<summary>英文:</summary>
I have a cleansed pandas dataframe that just contains a single column of zip codes, and I'm trying to use pyzipcode to return the corresponding state in a new column by executing:
from pyzipcode import ZipCodeDatabase
import pandas as pd
import os
zcdb = ZipCodeDatabase()
df = pd.read_excel(r'G:\Downloads\testzip.xlsx')
df[pd.to_numeric(df['Zip'], errors='coerce').notnull()]
df = df.dropna
df['state'] = df['Zip'].map(lambda x: zcdb[x].state)
Unfortunately, I get the following error:
'method' object is not subscriptable
No idea why. Anyone know what's happening here?
</details>
# 答案1
**得分**: 2
`df = df.dropna` 用它的 `dropna` 方法替换了你的数据框。这导致 `df['Zip']` 引发了你所看到的异常。将其替换为 `df = df.dropna()`,这将调用方法,我相当确定这是你想要的。
<details>
<summary>英文:</summary>
`df = df.dropna` replaces your dataframe by its `dropna` method. This causes `df['Zip']` to raise the exception you see. Replace it with `df = df.dropna()`, which calls the method instead - I am fairly sure that's what you want.
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论