簡體   English   中英

有條件地連接兩列的最佳/簡潔方法 Pandas DataFrame

[英]Best/Concise Way to Conditionally Concat two Columns in Pandas DataFrame

我正在嘗試有條件地連接 Pandas DataFrame 中的兩列。

我找到了一個相關的答案,我在下面對其進行了改編 - 但似乎應該有一種更簡潔的方法來做到這一點。 在R和dplyr或者data.table,這是比較簡單的一行代碼。

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

它也只是一個使用datar的單行代碼:

>>> from datar.all import f, tibble, mutate, if_else, paste0
>>> data = {"Product": ["Shorts", "T-Shirt", "Jacket", "Cap"],
...         "Color": ["Red", "Blue", "White", "Green"],
...         "Size": ["S", "M", None, "S"]}
>>> df = tibble(**data)
>>> df >> mutate(Output=if_else(f.Size == "S", paste0(f.Product, " (", f.Color, ")"), f.Color))
   Product    Color     Size        Output
  <object> <object> <object>      <object>
0   Shorts      Red        S  Shorts (Red)
1  T-Shirt     Blue        M          Blue
2   Jacket    White     None         White
3      Cap    Green        S   Cap (Green)

我是 datar 的作者,它是由 pandas 支持的 python package 以在 R 中實現dplyr的語法。

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']
)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM