【问题标题】:Best/Concise Way to Conditionally Concat two Columns in Pandas DataFrame在 Pandas DataFrame 中有条件地连接两列的最佳/简洁方法
【发布时间】:2022-01-03 22:35:12
【问题描述】:

我正在尝试有条件地连接 Pandas DataFrame 中的两列。

我找到了一个相关的answer,我在下面对其进行了改编——但似乎应该有一种更简洁的方法来做到这一点。在带有 dplyr 或 data.table 的 R 中,这是一行相对简单的代码。

import pandas as pd
import numpy as np

data = {"Product": ["Shorts", "T-Shirt", "Jacket", "Cap"],
        "Color": ["Red", "Blue", "White", "Green"],
        "Size": ["S", "M", None, "S"]}

df = pd.DataFrame(data)
df

# if size = 'S' then concatenate Product and Color, else just Put in the value from Color column


for index, row in df.iterrows():
    if row['Size'] == 'S':
        df.loc[index, 'Output'] = str(row['Product']) + " (" + str(row['Color']) + ')'
    else:
        df.loc[index, 'Output'] = str(row['Color'])
        
        
df

【问题讨论】:

    标签: python pandas dataframe concatenation


    【解决方案1】:

    np.where 用于有条件地生成列值。第一个参数是条件,然后是 True 值,然后是 False 值。在这种情况下,这可能是这样的:

    df['Output'] = np.where(
        df['Size'].eq('S'),  # Condition
        df['Product'].astype(str) + df['Color'].map(' ({})'.format),  # Where True
        df['Color']  # Where False
    )
    

    df:

       Product  Color  Size        Output
    0   Shorts    Red     S  Shorts (Red)
    1  T-Shirt   Blue     M          Blue
    2   Jacket  White  None         White
    3      Cap  Green     S   Cap (Green)
    

    注意:map 与格式字符串一起使用,因为它比多个字符串连接产生的副本更少,因此速度更快,但也可以这样做:

    df['Output'] = np.where(
        df['Size'] == 'S',
        df['Product'].astype(str) + ' (' + df['Color'].astype(str) + ')',
        df['Color']
    )
    

    【讨论】:

      猜你喜欢
      • 2015-11-29
      • 1970-01-01
      • 2021-09-27
      • 1970-01-01
      • 2014-09-18
      • 1970-01-01
      • 1970-01-01
      • 2016-07-14
      • 2018-07-18
      相关资源
      最近更新 更多