[英]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.