【问题标题】:In Python Pandas, how do I combine two columns containing strings using if/else statement or similar?在 Python Pandas 中,如何使用 if/else 语句或类似语句组合包含字符串的两列?
【发布时间】:2020-07-21 03:17:43
【问题描述】:

我从一个 excel 文件创建了一个 pandas 数据框,其中前两列是:

df = pd.DataFrame({'0':['','','Location Code','pH','Ag','Alkalinity'], '1':['Lab Id','Collection Date','','','µg/L','mg/L']})

看起来像这样:

         df[0]           df[1]
                        Lab Id
               Collection Date
Location Code                 
           pH                 
           Ag             µg/L
   Alkalinity             mg/L

我想将这些列合并为如下所示的列:

           df[0]
          Lab Id
 Collection Date
   Location Code
              pH
        Ag (µg/L)
Alkalinity (mg/L)

我认为在组合 df[0] 和 df[1] 之前我需要一个控制语句,如下所示:

if **there is a blank space in either column, then it performs**:
   df[0] = df[0].astype(str)+df[1].astype(str)
else:
   df[0] = df[0].astype(str)+' ('+df[1].astype(str)+')'

但我不确定如何编写 if 语句。谁能在这里指导我。 非常感谢。

【问题讨论】:

    标签: python-3.x pandas string if-statement


    【解决方案1】:

    我们可以试试np.select

    cond=[(df['0']=='') & (df['1']!=''), (df['0']!='') & (df['1']==''), (df['0']!='') & (df['1'] !='')]
    val=[df['1'], df['0'], df['0']+ '('+df['1']+')']
    df['new']=np.select(cond,val)
    df
                   0                1               new
    0                          Lab Id            Lab Id
    1                 Collection Date   Collection Date
    2  Location Code                      Location Code
    3             pH                                 pH
    4             Ag             µg/L          Ag(µg/L)
    5     Alkalinity             mg/L  Alkalinity(mg/L)
    

    【讨论】:

    • 谢谢@YOBEN_S。有效!我只是将df['0'] 更改为df[0] 等等。另外,我希望新合并的列 df['new'] 替换 df[0]
    【解决方案2】:

    如果值为 Na,则可能:

    df['result'] = df[0].fillna(df[1])
    

    【讨论】:

      【解决方案3】:

      这使用numpy where 工作,字符串连接假设基于共享的数据:

      df.assign(
          merger=np.where(
              df["1"].str.endswith("/L"),
              df["0"].str.cat(df["1"], "(").add(")"),
              df["0"].str.cat(df["1"], ""),
          )
      )
      
             0                 1              merger
      0                      Lab Id           Lab Id
      1                      Collection Date  Collection Date
      2   Location Code                       Location Code
      3   pH                                   pH
      4   Ag                 µg/L              Ag(µg/L)
      5   Alkalinity  mg/L                     Alkalinity(mg/L)
      

      或者,如果这是您所追求的,您可以将其分配给“0”:

      df["0"] = np.where(
          df["1"].str.endswith("/L"),
          df["0"].str.cat(df["1"], "(").add(")"),
          df["0"].str.cat(df["1"], ""),
      )
      

      【讨论】:

        【解决方案4】:

        这是另一种方式:

        首先你用值+'()'替换你要去concat的值

        df['1'].loc[df.replace('', np.nan).notnull().all(axis =1 )] = '(' + df['1'] + ')'
        

        现在我们用bfillffill填充缺失值

        df = df.replace('', np.nan).bfill(axis = 1).ffill(axis = 1)
        

        唯一剩下的就是在有括号的地方合并值

         df.loc[:, 'merge'] = np.where(df['1'].str.endswith(')'), df['0'] + df['1'], df['1'])
        

        【讨论】:

          【解决方案5】:

          通过DataFrame.eqDataFrame.any 测试至少一列0,1 中是否为空值,然后像numpy.where 中的答案一样加入这两列:

          df = pd.DataFrame({0:['','','Location Code','pH','Ag','Alkalinity'], 
                             1:['Lab Id','Collection Date','','',u'µg/L','mg/L']})
          
          
          print (df[[0,1]].eq(''))
                 0      1
          0   True  False
          1   True  False
          2  False   True
          3  False   True
          4  False  False
          5  False  False
          
          print (df[[0,1]].eq('').any(axis=1))
          0     True
          1     True
          2     True
          3     True
          4    False
          5    False
          dtype: bool
          
          df[0] = np.where(df[[0,1]].eq('').any(axis=1), 
                           df[0].astype(str)+df[1].astype(str),
                           df[0].astype(str)+' ('+df[1].astype(str)+')')
          print (df)
                             0                1
          0             Lab Id           Lab Id
          1    Collection Date  Collection Date
          2      Location Code                 
          3                 pH                 
          4          Ag (µg/L)             µg/L
          5  Alkalinity (mg/L)             mg/L
          

          【讨论】:

            猜你喜欢
            • 2018-03-09
            • 1970-01-01
            • 2014-03-02
            • 1970-01-01
            • 2013-03-09
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多