【问题标题】:Check if string in a column, then return value from another column at the same index检查列中是否有字符串,然后从同一索引的另一列返回值
【发布时间】:2022-11-10 23:49:18
【问题描述】:
Contact Old Contact
234255 987778
343556 987877
Missing 984567
Missing
Missing 845665
343556 789998

鉴于上表,我希望浏览“联系人”下的每一行并检查是否丢失。如果该行有缺失,请使用相应的“旧联系人”值代替文本“缺失”。如果旧联系人为空,则将其保留为“缺失”

所需表:

Contact Old Contact
234255 987778
343556 987877
984567 984567
Missing
845665 845665
343556 789998
df['Contact'] = df['Contact'].apply(
    lambda x: df['Old Contact'] if "Missing" in x else x)

上面的行给了我整列“旧联系人”缺失的地方。我不确定如何在这里使用索引来获得我想要的东西。提前致谢!

【问题讨论】:

  • 你可以检查df["contact"] = np.where("Missing" in df['Old Contact'], df['Old Contact'], df['contact'])

标签: python pandas dataframe apply


【解决方案1】:

使用mask

df['Contact'].mask(df['Contact'].eq('Missing'), df['Old Contact'].fillna('Missing'))

输出:

0      234255
1      343556
2      984567
3     Missing
4      845665
5      343556
Name: Contact, dtype: object

使结果到Contact

【讨论】:

    【解决方案2】:

    我有一段时间没有使用熊猫了,所以我确信有更好的解决方案,但蛮力方法可能是:

    for idx in df.index:
        if (df.iloc[idx]['Contact']=='Missing'):
            if len(df.iloc[idx]['Old Contact'].strip()):
                df.iloc[idx]['Contact']=df.iloc[idx]['Old Contact']
    

    【讨论】:

      【解决方案3】:

      使用.where.assign

      df = df.assign(
          Contact=df["Contact"].where(df["Contact"].ne("Missing"), df["Old Contact"]).fillna("Missing")
      ).fillna("")
      print(df)
      
          Contact Old Contact
      0    234255    987778.0
      1    343556    987877.0
      2  984567.0    984567.0
      3   Missing            
      4  845665.0    845665.0
      5    343556    789998.0
      

      【讨论】:

        【解决方案4】:

        您有两个要检查的条件。您可以在多个条件 if 语句 (https://www.geeksforgeeks.org/check-multiple-conditions-in-if-statement-python/) 中检查这两个条件,同时遍历 df.index 中的每个条目。

        for idx in df.index:
            if (df.iloc[idx]['Contact']=='Missing') & (df.iloc[idx]['Old Contact']!=''):
                df.iloc[idx]['Contact']=df.iloc[idx]['Old Contact']
            elif (df.iloc[idx]['Contact']=='Missing') & (df.iloc[idx]['Old Contact']==''):
                df.iloc[idx]['Contact']='Missing'
            else: pass
        

        输出:

        df
        
            Contact Old Contact
        0   234255  987778
        1   343556  987877
        2   984567  984567
        3   Missing 
        4   845665  845665
        5   343556  789998
        

        【讨论】:

          猜你喜欢
          • 2020-03-15
          • 2014-12-10
          • 2021-12-29
          • 2017-06-17
          • 2021-11-26
          • 1970-01-01
          • 1970-01-01
          • 2017-10-06
          • 2015-12-18
          相关资源
          最近更新 更多