使用字典来重新映射Pandas DataFrame列中的值

使用字典来重新映射Pandas DataFrame列中的值

在Python的Pandas中处理数据时,我们对数据进行了大量的操作,以获得所需的数据形式。其中一个操作可能是我们想重新映射DataFrame中某一列的值。让我们来讨论几种我们可以做到的方法。

创建Pandas数据框架以重新映射数值

给出一个包含事件数据的数据框架,将特定列的值重新映射为一个新的值。

# importing pandas as pd
import pandas as pd
 
# Creating the DataFrame
df = 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 dataframe
print(df)
Python

输出:

使用字典来重新映射Pandas DataFrame列中的值

使用replace()函数对Pandas列中的数值进行映射

现在我们将使用replace()函数将’Event’列的值按其各自的代码重新映射。

# Create a dictionary using which we
# will remap the values
dict = {'Music' : 'M', 'Poetry' : 'P', 'Theatre' : 'T', 'Comedy' : 'C'}
 
# Print the dictionary
print(dict)
 
# Remap the values of the dataframe
df.replace({"Event": dict})
Python

输出 :

使用字典来重新映射Pandas DataFrame列中的值

使用字典来重新映射Pandas DataFrame列中的值

使用map()函数对Pandas DataFrame列中的数值进行映射

现在我们将使用map()函数将’Event’列的值按其各自的代码重新映射。

# Create a dictionary using which we
# will remap the values
dict = {'Music': 'M', 'Poetry': 'P', 'Theatre': 'T', 'Comedy': 'C'}
 
# Print the dictionary
print(dict)
 
# Remap the values of the dataframe
df['Event'] = df['Event'].map(dict)
 
# Print the DataFrame after modification
print(df)
Python

输出:

使用字典来重新映射Pandas DataFrame列中的值

使用字典来重新映射Pandas DataFrame列中的值

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册