将州映射到 pandas 数据框中的邮政编码

huangapple go评论140阅读模式
英文:

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&#39;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: 

&#39;method&#39; object is not subscriptable

No idea why. Anyone know what&#39;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[&#39;Zip&#39;]` to raise the exception you see. Replace it with `df = df.dropna()`, which calls the method instead - I am fairly sure that&#39;s what you want.

</details>



huangapple
  • 本文由 发表于 2023年8月11日 03:54:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/76878926.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定