Очистите строковые данные в данном кадре данных Pandas
Как мы знаем, в современном мире аналитикой данных пользуются самые разные компании. Работая с данными, мы можем столкнуться с любыми проблемами, требующими нестандартного подхода к оценке. Большая часть Данных в реальной жизни содержит названия сущностей или другие существительные. Возможно, имена имеют неправильный формат. В этом посте мы обсудим подходы к очистке таких данных.
Предположим, мы имеем дело с данными веб-сайта электронной коммерции. Название товаров не в правильном формате. Правильно отформатируйте данные так, чтобы в начале и в конце не было пробелов, а первые буквы всех продуктов были заглавными.
Solution #1: Many times we will come across a situation where we are required to write our own customized function suited for the task at hand.
# importing pandas as pdimport pandas as pd # Create the dataframedf = pd.DataFrame({"Date":["10/2/2011", "11/2/2011", "12/2/2011", "13/2/2011"], "Product":[" UMbreLla", " maTress", "BaDmintoN ", "Shuttle"], "Updated_Price":[1250, 1450, 1550, 400], "Discount":[10, 8, 15, 10]}) # Print the dataframeprint(df) |
Выход :

Now we will writer our own customized function to solve this problem.
def Format_data(df): # iterate over all the rows for i in range(df.shape[0]): # reassign the values to the product column # we first strip the whitespaces using strip() function # then we capitalize the first letter using capitalize() function df.iat[i, 1]= df.iat[i, 1].strip().capitalize() # Let"s call the functionFormat_data(df) # Print the Dataframeprint(df) |
Выход :
Solution #2 : Now we will see a better and efficient approach using Pandas DataFrame.apply() function.
# importing pandas as pdimport pandas as pd # Create the dataframedf = pd.DataFrame({""Date":["10/2/2011", "11/2/2011", "12/2/2011", "13/2/2011"], "Product":[" UMbreLla", " maTress", "BaDmintoN ", "Shuttle"], "Updated_Price":[1250, 1450, 1550, 400], "Discount":[10, 8, 15, 10]}) # Print the dataframeprint(df) |
Выход :

Let’s use the Pandas DataFrame.apply() function to format the Product names in the right format. Inside the Pandas DataFrame.apply() function we will use lambda function.
# Using the df.apply() function on product columndf["Product"] = df["Product"].apply(lambda x : x.strip().capitalize()) # Print the Dataframeprint(df) |
Выход :
Внимание компьютерщик! Укрепите свои основы с помощью базового курса программирования Python и изучите основы.
Для начала подготовьтесь к собеседованию. Расширьте свои концепции структур данных с помощью курса Python DS. А чтобы начать свое путешествие по машинному обучению, присоединяйтесь к курсу Машинное обучение - базовый уровень.