简体   繁体   中英

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. 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. Currently, I cannot write the states to OriginalZipcode column in excel. 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:

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

You can add the OriginalState column without iterating the 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.

This should do the trick.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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