繁体   English   中英

使用Pandas在Python中编写Excel值

[英]Writing values to excel in python using pandas

我是python的新手,想将excel文件中的ZipCode传递给“ uszipcode”包,并将该特定zipcode的状态写入excel工作表的“ OriginalZipcode”列。 这样做的原因是,我想将现有状态与原始状态进行比较。 我不明白代码中的for循环是否错误或其他错误。 目前,我无法将状态写入Excel中的OriginalZipcode列。 我写的代码是:

import pandas as pd
from pandas import ExcelWriter
from pandas import ExcelFile
import uszipcode as US
from uszipcode import ZipcodeSearchEngine
search = ZipcodeSearchEngine()
df = pd.read_excel("H:\excel\checking for zip and states\checkZipStates.xlsx", sheet_name='Sheet1')
#print(df.values)
for i, row in df.iterrows():
    zipcode = search.by_zipcode(row['ZipCode']) #for searching zipcode
    b = zipcode.State
    df.at['row','OriginalState'] = b
    df.to_excel("H:\\excel\\checking for zip and states\\new.xlsx", sheet_name = "compare", index = False)

Excel工作表的格式如下:

| ZipCode   |CurrentState     | OriginalState |
|-----------|-----------------|---------------|
| 59714     | Montana         |               |
| 29620     | South Carolina  |               |
| 54405     | Wisconsin       |               |
|    .      | .               |               |
|    .      | .               |               |

您可以添加OriginalState列,而无需迭代df:

定义一个函数,该函数针对任何给定的邮政编码返回所需的值:

def get_original_state(state):
    zipcode = search.by_zipcode(state) #for searching zipcode
    return zipcode.State

然后:

df['OriginalState'] = df.apply( lambda row: get_original_state(row['ZipCode']), axis=1)

最后,仅将df导出一次即可。

这应该可以解决问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM