【问题标题】:How to select a column per row based on multiple conditions in pandas如何根据熊猫中的多个条件每行选择一列
【发布时间】:2020-05-21 17:34:23
【问题描述】:

我有以下名为 df 的数据框:

    Identifier   Name1   Name2     Country   Otherdata.......
0   N102314      BDH.A   0123      AUS
1   D19u248      DDF     DDF.X     DEN
2   J19j09f      XXG.X   XXG.DD    GER
3   Jd139jf      D07.SS  D07       SG
4   Jh39222      DEE     DEE.O     US
5   HH819jf      HHD.OH  HHD       MX
6   Jajh393      HXX     HXX.K     US  
7   DeeaJJd      MSS.O   DEX.O     US 

我想创建一个名为 Name0 的新列,在此我根据以下条件为每行选择一列。

如果 Country == "US",请始终为 Name0 选择 Name1 中的内容。

否则,请检查哪个名称包含“.”,然后选择该项目作为 Name0。 如果 Name1 和 Name2 都包含一个点,则在 Name0 中打印单词 NAMEERROR。

所以最后一帧会是这样的:

    Identifier   Name1   Name2     Country  Name0      NOTES....... 
0   N102314      BDH.A   0123      AUS      BDH.A      #not US so chose the one with the "."
1   D19u248      DDF     DDF.X     DEN      DDF.X      #not US so chose the one with the "."
2   J19j09f      XXG.X   XXG.DD    GER      NAMEERROR  #not US and both contains ".", print NAMEERROR
3   Jd139jf      D07.SS  D07       SG       D07.SS     #not US so chose the one with the "."
4   Jh39222      DEE     DEE.O     US       DEE        #US so chose Name1
5   HH819jf      HHD.OH  HHD       MX       HHD.OH     #not US so chose the one with the "."
6   Jajh393      HXX     HXX.K     US       HXX        #US so chose Name1
7   DeeaJJd      MSS.O   DEX.O     US       MSS.O      #both contain "." but US so chose Name1

我在想它可能看起来像第一部分

df['Name0'] = np.NaN
df['Name0'] = np.where(df['Country'].str.contains('US'),df['Name1'],df['Name0'])

但我不知道从哪里开始。

【问题讨论】:

    标签: python regex string pandas dataframe


    【解决方案1】:

    apply 在这里很方便。

    def fix(country, n1, n2):
        if country == 'US':
            return n1
        else:
            if ('.' in n1) & ('.' in n2):
                return 'NAMERERROR'
            elif '.' in n1:
                return n1
            elif '.' in n2:
                return n2
    
    
    df['Name0'] = df.apply(lambda x: fix(country=x['Country'],
                                         n1 = x['Name1'],
                                         n2 = x['Name2']), axis=1)
    

    【讨论】:

    • 我得到这个错误 in fix(country, n1, n2) 5 return n1 6 else: ----> 7 if ('.' in n1) & ('.' in n2): 8 return 'NAMERERROR' 9 elif '.'在 n1 中:TypeError:'float' 类型的参数不可迭代
    • Name1Name2的数据类型是什么?它们必须是字符串才能使此功能正常工作。您可以通过执行df.dtypes 来检查
    • df.dtypes 是否为Name1Name2 显示object
    • 好的,现在可以了,我必须在合并之前和合并之后输入它们
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-28
    • 1970-01-01
    • 2016-07-24
    • 1970-01-01
    相关资源
    最近更新 更多