Использование словаря для переназначения значений в столбцах Pandas DataFrame
Работая с данными в Pandas, мы выполняем широкий спектр операций с данными, чтобы получить данные в желаемой форме. Одна из этих операций может заключаться в том, что мы хотим переназначить значения определенного столбца в DataFrame. Давайте обсудим несколько способов, которыми мы можем это сделать.
Учитывая Dataframe, содержащий данные о событии, переназначьте значения определенного столбца на новое значение.
Code #1: We can use DataFrame.replace() function to achieve this task. Let’s see how we can do that.
# importing pandas as pdimport pandas as pd # Creating the DataFramedf = pd.DataFrame({"Date":["10/2/2011", "11/2/2011", "12/2/2011", "13/2/2011"], "Event":["Music", "Poetry", "Theatre", "Comedy"], "Cost":[10000, 5000, 15000, 2000]}) # Print the dataframeprint(df) |
Выход :
Теперь мы переназначим значения столбца «Событие» по их соответствующим кодам.
# Create a dictionary using which we# will remap the valuesdict = {"Music" : "M", "Poetry" : "P", "Theatre" : "T", "Comedy" : "C"} # Print the dictionaryprint(dict) # Remap the values of the dataframedf.replace({"Event": dict}) |
Выход : 

Code #2: We can use map() function to achieve this task.
# importing pandas as pdimport pandas as pd # Creating the DataFramedf = pd.DataFrame({"Date":["10/2/2011", "11/2/2011", "12/2/2011", "13/2/2011"], "Event":["Music", "Poetry", "Theatre", "Comedy"], "Cost":[10000, 5000, 15000, 2000]}) # Print the dataframeprint(df) |
Выход :

Now we will remap the values of the ‘Event’ column by their respective codes.
# Create a dictionary using which we# will remap the valuesdict = {"Music" : "M", "Poetry" : "P", "Theatre" : "T", "Comedy" : "C"} # Print the dictionaryprint(dict) # Remap the values of the dataframedf["Event"]= df["Event"].map(dict) # Print the DataFrame after modificationprint(df) |
Выход : 

Внимание компьютерщик! Укрепите свои основы с помощью базового курса программирования Python и изучите основы.
Для начала подготовьтесь к собеседованию. Расширьте свои концепции структур данных с помощью курса Python DS. А чтобы начать свое путешествие по машинному обучению, присоединяйтесь к курсу Машинное обучение - базовый уровень.