更多、更及时内容欢迎留意微信公众号: 小窗幽记机器学习
背景
DataFrame数据中一列的值需要根据某个字典批量映射为字典中的value。
方法1:pandas中的df.replace
import pandas as pd
import numpy as np
df = pd.DataFrame({'col2': {0: 'a', 1: 2, 2: np.nan}, 'col1': {0: 'w', 1: 1, 2: 2}})
print("init df:")
print(df)
column_dict = {1: "A", 2: "B"}
new_df = df.replace({"col1": column_dict})
print("use dict to replace one column,dict=", column_dict)
print("new df:")
print(new_df)
运行结果:
init df:
col2 col1
0 a w
1 2 1
2 NaN 2
use dict to replace one column,dict= {1: 'A', 2: 'B'}
new df:
col2 col1
0 a w
1 2 A
2 NaN B
方法2:map操作
import pandas as pd
import numpy as np
df = pd.DataFrame({'col2': {0: 'a', 1: 2, 2: np.nan}, 'col1': {0: 'w', 1: 1, 2: 2}})
print("init df:")
print(df)
column_dict = {1: "A", 2: "B"}
# new_df = df.replace({"col1": column_dict})
df['col1'] = df['col1'].map(column_dict)
print("use dict to replace one column,dict=", column_dict)
print("new df:")
print(df)
运行结果:
init df:
col2 col1
0 a w
1 2 1
2 NaN 2
use dict to replace one column,dict= {1: 'A', 2: 'B'}
new df:
col2 col1
0 a NaN
1 2 A
2 NaN B
PS:
数据量大的情况下,map会比 replace 要快。
【更多、更及时内容欢迎留意微信公众号: 小窗幽记机器学习 】