【问题标题】:How do I conditionally map only the empty rows of a column?如何有条件地仅映射列的空行?
【发布时间】:2018-09-19 09:09:47
【问题描述】:

如何创建一个映射到字典的新数据框列,但仅适用于空白行,同时保留非空白行的引用列的值?下面我通过将“col1”映射到 x 创建了“新 col”,但我希望仅在“col2”为空的情况下映射到 x,否则使用 col2 中的值。

import pandas as pd
x = {'three':'green','four':'purple','five':'orange'}
d = {'col1': ['three', 'four', 'five'], 'col2':['blue',"","red"]}
df = pd.DataFrame(data=d)
df['new col']=df['col1'].map(x)

实际结果:

    col1  col2  new col
0   three blue   green
1   four         purple
2   five  red    orange

期望的结果(新的 col 保留第 0 行和第 2 行中的值 'blue' 和 'red',但将第 1 行映射到 x):

    col1  col2   new col
0   three  blue  blue
1   four         purple
2   five    red  red

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    使用np.where

    df['newcol']=np.where(df.col2=='',df.col1.map(x),df.col2)
    df
    Out[607]: 
        col1  col2  newcol
    0  three  blue    blue
    1   four        purple
    2   five   red     red
    

    【讨论】:

    • df.col2.isnull() 可能更合适。
    • isnull() 不会检测空字符串,这里需要进行相等性检查
    • df.col2.isnull() 实际上对我有用...谢谢!
    【解决方案2】:

    使用maskfillna

    df.col2.mask(df.col2.eq('')).fillna(df.col1.map(x))
    

    0      blue
    1    purple
    2       red
    Name: col2, dtype: object
    

    df.assign(newcol=df.col2.mask(df.col2.eq('')).fillna(df.col1.map(x)))
    

        col1  col2  newcol
    0  three  blue    blue
    1   four        purple
    2   five   red     red
    

    使用loc 的就地选项:

    这个选项比np.wheremask 都慢,但清楚地展示了我们在做什么。

    df['newcol'] = df.col2
    df.loc[df.col2.eq(''), 'newcol'] = df.col1.map(x)
    

    【讨论】:

      【解决方案3】:

      使用pandas.DataFrame.apply

      df['new col'] = df.apply(
          lambda row: x[row['col1']] if row['col2'] == '' else row['col2'], axis=1)
      

      【讨论】:

        猜你喜欢
        • 2018-08-25
        • 1970-01-01
        • 2018-04-22
        • 2022-12-02
        • 2020-10-05
        • 1970-01-01
        • 2020-04-27
        • 2022-11-17
        • 2020-11-25
        相关资源
        最近更新 更多