[英]How to map state code from one csv file to state name in another csv file in python?
[英]Map State name using state code Using Python
我目前有 2 個 csv 文件。 The CSV file on which i am performing is having Some values as state codes and some as state Names, I want to replace the state code with the state names.
CSV 1
state
Assam
Goa
06
Kerala
12
CSV 2
S.No state_name state_code
1 Karnataka 06
2 Mizoram 12
3 Meghalaya 15
CSV 1 中需要 OUTPUT:
state
Assam
Goa
Karnataka
Kerala
Mizoram
到目前為止我已經嘗試過:
df= pd.read_csv("csv1.csv")
data1 = pd.read_csv("csv1.csv")
for index, row in df.iterrows():
for index_config, row_config in data1.iterrows():
if row['state'] == row_config['']:
df['state'] = row_config['State']
How i can map the state_name from CSV 2 in place of state code values in state column of CSV 1
讓我們首先創建一個映射dictionary
,然后對第一個數據幀( df1
)使用replace
方法:
#df1 is for CSV1 and df2 is for CSV2 file
mapping = dict(zip(df2['state_code'], df2['state_name']))
#print(mapping)
#{'06': 'Karnataka', '12': 'Mizoram', '15': 'Meghalaya'}
df1['state'] = df1.state.replace(mapping)
Output:
state
0 Assam
1 Goa
2 Karnataka
3 Kerala
4 Mizoram
您可以使用@Quang Huang的評論,但在閱讀csv2
時需要額外設置dtype={'state_code': str}
步驟。 否則state_code
將被解析為int
並且不會像預期的那樣 map ( 6
vs 06
)。
df = pd.read_csv('csv1.csv')
data1 = pd.read_csv('csv2.csv', dtype={'state_code': str})
df['state'] = df['state'].replace(data1.set_index('state_code')['state_name'])
state
0 Assam
1 Goa
2 Karnataka
3 Kerala
4 Mizoram
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.