I want to replace the "magneticfields\nD" in the Magnetic Declination column. I am generating this csv file from API. File look like this.
import requests
import json
import pandas as pd
import os
import csv
from pathlib import Path
parameters = {
"latd": 88, # [deg]
"latm": 00, # [deg]
"lats": 00, # [deg]
"lond": 75, # [deg]
"lonm": 00, # [deg]
"lons": 00, # [deg]
"elev" : 00, # [km]
"year" : None, # [YYYY]
"month" : '07', # [MM]
"day": '01', # [DD]
"Ein": 'D' # [Model]
}
hostname = "https://api.geomagnetism.ga.gov.au/agrf"
df_1=pd.DataFrame()
for year in range(1985, 2025):
try:
parameters["year"] = year
response = requests.get(hostname, params= dict(parameters, ps=str(year)))
# extract JSON payload of response as Python dictionary
json_payload = response.json()
# raise an Exception if we encoutnered any HTTP error codes like 404
response.raise_for_status()
except requests.exceptions.ConnectionError as e:
# handle any typo errors in url or endpoint, or just patchy internet connection
print(e)
except requests.exceptions.HTTPError as e:
# handle HTTP error codes in the response
print(e, json_payload['error'])
except requests.exceptions.RequestException as e:
# general error handling
print(e, json_payload['error'])
else:
json_payload = response.json()
#print(json.dumps(json_payload, indent=4, sort_keys=True))
df = pd.DataFrame(json_payload)
print(df)
print(df.loc[['D'],['magneticFields']])
new_row = {
"SourceFile": hostname,
"Year": year,
"Magnetic Declination": df.loc[['D'],['magneticFields']],
"Latitude": 88,
"Longitude": 75
}
df_1 = df_1.append(new_row, ignore_index=True)
df_1 = df_1[['Year', 'Latitude', 'Longitude','Magnetic Declination','SourceFile']]
#df_1['Magnetic Declination'] = df_1['Magnetic Declination'].apply(lambda x: x.replace(r"magneticFields\nD ", ""))
#df_1['Magnetic Declination'] = df_1['Magnetic Declination'].str.replace(r"..magneticFields\nD.....","",regex=True)
#df_1['Magnetic Declination'] = df_1['Magnetic Declination'].str.replace('magneticFields\nD', '').astype(str)
df_1["Magnetic Declination"] = df_1["Magnetic Declination"].apply(lambda x: x.replace(" deg", ""))
df_1.to_csv('magnetic_declination_australia_1.csv',index=False)
Tried all the methods but none of them is working.
df_1['Magnetic Declination'] = df_1['Magnetic Declination'].apply(lambda x: x.replace(r"magneticFields\nD ", ""))
df_1['Magnetic Declination'] = df_1['Magnetic Declination'].str.replace(r"..magneticFields\nD.....","",regex=True)
df_1['Magnetic Declination'] = df_1['Magnetic Declination'].str.replace('magneticFields\nD', '').astype(str)
Output should look this.
Can anyone help me how to fixed this? csv file that is generating from API attached here.