簡體   English   中英

Pandas DataFrame 列字符串連接

[英]Pandas DataFrame column string concatenation

我有一個帶有一列字符串的 df ,如下所示:

      col1         
         a            
         b            
         c            
         d            

我還有一個字符串變量x = 'x'和一個字符串列表list1 = ['ax', cx']

我想創建一個新列來檢查col1 + x的連接字符串是否在 list1 中。 如果是,則 col2 = 1 否則 col2 = 0。

這是我的嘗試:

df['col2'] = 1 if str(df['col1'] + x) in list1 else 0

哪個不起作用。

df['col2'] = 1 if df['col1'] + x in list1 else 0

也不行。

格式化這個的正確方法是什么? 感謝您的任何幫助。

      col1         col2  <-- should be this
         a            1
         b            0
         c            1
         d            0

您可以按如下方式使用map功能。

df['col2'] = df['col1'].map(lambda val: 1 if x + val in list1 else 0)

使用isin

df['col2'] = df.col1.add('x').isin(list1).astype(int)

#  col1  col2
#0    a     1
#1    b     0
#2    c     1
#3    d     0

檢查結果

使用apply的另一種解決方案:

import pandas as pd

df = pd.DataFrame({'col1': ['a','b','c', 'd']})

def func(row):
    list1 = {'ax', 'cx'}
    row['col2'] = 1 if row.col1 + 'x' in list1 else 0
    return row

df2 = df.apply(func, axis='columns')

# OUTPUTS : 
#  col1  col2
#0    a     1
#1    b     0
#2    c     1
#3    d     0

暫無
暫無

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

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