简体   繁体   English

使用Pandas在Python中编写Excel值

[英]Writing values to excel in python using pandas

I'm new to python and would like to pass the ZipCode in excel file to 'uszipcode' package and write the state for that particular zipcode to 'OriginalZipcode' column in the excel sheet. 我是python的新手,想将excel文件中的ZipCode传递给“ uszipcode”包,并将该特定zipcode的状态写入excel工作表的“ OriginalZipcode”列。 The reason for doing this is, I want to compare the existing states with the original states. 这样做的原因是,我想将现有状态与原始状态进行比较。 I don't understand if the for loop is wrong in the code or something else is. 我不明白代码中的for循环是否错误或其他错误。 Currently, I cannot write the states to OriginalZipcode column in excel. 目前,我无法将状态写入Excel中的OriginalZipcode列。 The code I've written is: 我写的代码是:

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)

The excel sheet is in this format: Excel工作表的格式如下:

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

You can add the OriginalState column without iterating the df: 您可以添加OriginalState列,而无需迭代df:

Define a function that returns the value you want for any given zip code: 定义一个函数,该函数针对任何给定的邮政编码返回所需的值:

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

Then: 然后:

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

Finally, export only once the df to excel. 最后,仅将df导出一次即可。

This should do the trick. 这应该可以解决问题。

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

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