【问题标题】:If there is a second column present then populate second column values, else populate first column values in Dataframe如果存在第二列,则填充第二列值,否则在 Dataframe 中填充第一列值
【发布时间】:2021-10-22 21:39:00
【问题描述】:

我有一个如下所示的数据框:

col_a1, col_a2, col_b1, col_b2
 abc                     lmn
 def     ghi             qrs
 zxv                     vbn
 pej             iop     qaz
 eki     lod     yhe     wqe

我现在需要两列,A 列和 B 列。条件汇总:

Column A = col_a2 if col_a2 is present else col_a1  
Column B = col_a1 if col_a1 is present else col_b2

所需的数据框应如下所示:

 Column A Column B
    abc    lmn
    ghi    qrs
    zxv    vbn
    pej    iop
    lod    yhe

【问题讨论】:

  • 我认为Column B = col_a1 if col_a1... 不是你的意思:o?

标签: python pandas dataframe data-science data-wrangling


【解决方案1】:

试试:

df['A'] = df.apply(lambda x: x['col_a2'] if x['col_a2'] != '' else x['col_a1'], axis=1)
df['B'] = df.apply(lambda x: x['col_b1'] if x['col_b1'] != '' else x['col_b2'], axis=1)
print(df[['A', 'B']])

    A       B
0   abc     lmn
1   ghi     qrs
2   zxv     vbn
3   pej     iop
4   lod     yhe

如果单元格中确实没有任何内容,!='' 将起作用(而不是 NaN 等)。如果您有实际的 NaN 值,请使用:

df['A'] = df.apply(lambda x: x['col_a2'] if pd.notna(x['col_a2']) else x['col_a1'], axis=1)
df['B'] = df.apply(lambda x: x['col_b1'] if pd.notna(x['col_b1']) else x['col_b2'], axis=1)

【讨论】:

    猜你喜欢
    • 2013-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-06
    • 1970-01-01
    相关资源
    最近更新 更多