Jun-28-2022, 03:31 AM
Hi,
I am trying to sort rows of data in a pandas Dataframe using the .sort_values() function. The goal is to change the order so that the numbers are displayed from lowest to highest. When I select the column that I want (Inflation Yearly Basis) it reorders it in a randomized way. However, when I select another column from the same Dataframe (Inflation Monthly Basis) that has the same type of data, it displays properly from lowest to highest.
Appreciate any help –– thanks!
Here's the code:
I am trying to sort rows of data in a pandas Dataframe using the .sort_values() function. The goal is to change the order so that the numbers are displayed from lowest to highest. When I select the column that I want (Inflation Yearly Basis) it reorders it in a randomized way. However, when I select another column from the same Dataframe (Inflation Monthly Basis) that has the same type of data, it displays properly from lowest to highest.
Appreciate any help –– thanks!
Here's the code:
import pandas as pd import requests import json import pandas_datareader.data as webdata import matplotlib as mpl %matplotlib inline import matplotlib.pyplot as plt from matplotlib.pyplot import figure import datetime from datetime import date import numpy as np from bs4 import BeautifulSoup url = 'https://www.global-rates.com/en/economic-indicators/inflation/consumer-prices/cpi/cpi.aspx' r = requests.get(url) data = r.text soup = BeautifulSoup(data, 'lxml') data = [] table = soup.find('table', cellpadding="2") table_body = table rows = table_body.find_all('tr', {'class': lambda x : x.startswith('tabledata')}) for row in rows: cols = row.find_all('td') cols = [ele.text.strip() for ele in cols] data.append([ele for ele in cols if ele]) # Get rid of empty values global_cpi_rates = pd.DataFrame (data, columns = ['Name','Country/Region','Period','Inflation Monthly Basis','Inflation Yearly Basis']) global_cpi_rates = global_cpi_rates.sort_values('Inflation Yearly Basis') global_cpi_rates