【问题标题】:Create new column in DataFrame based on respective values in two different columns根据两个不同列中的各自值在 DataFrame 中创建新列
【发布时间】:2020-11-28 14:44:40
【问题描述】:

我有以下数据框:

cars = {'Brand': ['Honda Civic','Toyota Corolla','Ford Focus','No Brand'],
        'Country': ['Japan','No Country','United States','Germany']
        }

df = pd.DataFrame(cars, columns = ['Brand', 'Country'])
df.head(4)

            Brand        Country
0     Honda Civic          Japan
1  Toyota Corolla     No Country
2      Ford Focus  United States
3        No Brand        Germany

希望在数据框中创建一个新列,该列将根据“品牌”和“国家”列的值进行组合。如果 Brand 列中有“No Brand”值,则 Desc 列仅采用 Country 列中的值。如果 Country 列中有“No Country”值,则 Desc 列仅采用 Brand 列中的值。期望的输出:

            Brand        Country    Desc
0     Honda Civic          Japan    Honda Civic Japan
1  Toyota Corolla     No Country    Toyota Corolla
2      Ford Focus  United States    Ford Focus United States
3        No Brand        Germany    Germany

如果它检查一列中的字符串,我可以这样做,但不确定如何处理两列。现在我只能在我想要的条件下检查布尔值。

df['Desc'] = df['Brand'].str.contains("No Brand") | df['Country'].str.contains("No Country")

            Brand        Country    Desc
0     Honda Civic          Japan    False
1  Toyota Corolla     No Country    True
2      Ford Focus  United States    False
3        No Brand        Germany    True

我读到不建议迭代数据帧并避免这样做。

【问题讨论】:

    标签: python pandas numpy dataframe


    【解决方案1】:
    def get_desc(brand, country):
        return (brand if brand != 'No Brand' else '') +\
               (' ' + country if country != 'No Country' else '')
    
    
    df['Desc'] = df['Brand'].combine(df['Country'], get_desc)
    
    print(df.head(4))
    

    输出:

                Brand        Country                      Desc
    0     Honda Civic          Japan         Honda Civic Japan
    1  Toyota Corolla     No Country            Toyota Corolla
    2      Ford Focus  United States  Ford Focus United States
    3        No Brand        Germany                   Germany
    

    【讨论】:

      【解决方案2】:

      让我们concat 这两列然后使用str.replaceNo BrandNo Country 值替换为空字符串:

      df['Desc'] = (df['Brand'] + ' ' + df['Country']).str.replace(r'No Brand\s*|\s*No Country', '')
      

      结果:

                  Brand        Country                      Desc
      0     Honda Civic          Japan         Honda Civic Japan
      1  Toyota Corolla     No Country            Toyota Corolla
      2      Ford Focus  United States  Ford Focus United States
      3        No Brand        Germany                   Germany
      

      【讨论】:

        【解决方案3】:
        In [2]: cars = {'Brand': ['Honda Civic','Toyota Corolla','Ford Focus','No Brand'],
           ...:         'Country': ['Japan','No Country','United States','Germany']
           ...:         }
           ...: 
           ...: df = pd.DataFrame(cars, columns = ['Brand', 'Country'])
           ...: df
        Out[2]: 
                    Brand        Country
        0     Honda Civic          Japan
        1  Toyota Corolla     No Country
        2      Ford Focus  United States
        3        No Brand        Germany
        
        In [3]: df['New_col'] = (df.Brand + " " + df.Country).str.replace("No Brand", "").str.replace("No Country", "").str.strip()
        
        In [4]: df
        Out[4]: 
                    Brand        Country                   New_col
        0     Honda Civic          Japan         Honda Civic Japan
        1  Toyota Corolla     No Country            Toyota Corolla
        2      Ford Focus  United States  Ford Focus United States
        3        No Brand        Germany                   Germany
        
        

        【讨论】:

          猜你喜欢
          • 2020-09-10
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-02-15
          • 1970-01-01
          相关资源
          最近更新 更多