使用字典来重新映射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)
输出:
使用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})
输出 :
使用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)
输出: