pandas列值根據字典批量替換

JasonLiu1919發表於2020-12-23

背景

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 要快。

相關文章