第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

熊貓比較 2 列,只保留匹配的單詞字符串

熊貓比較 2 列,只保留匹配的單詞字符串

慕森王 2021-12-29 19:27:43
我正在嘗試將 1 個數(shù)據(jù)幀列中的單詞或刺與同一 df 中的另一列進行比較,并輸出僅包含匹配單詞的第三列。inputCol1the cat crossed a roadthe dog barkedthe chicken barkedCol2the cat alligatorsome words herechicken soupdesired resultCol3the catNULLchicken這就是我所擁有的,但出現(xiàn)錯誤。df[Col3] = df[Col1].apply(lambda x: ' '.join([word for word in x.split() if word in x[Col2].split(' ')]))錯誤是類型錯誤:字符串索引必須是整數(shù)
查看完整描述

3 回答

?
繁花不似錦

TA貢獻1851條經(jīng)驗 獲得超4個贊

使用apply, 和' '.join, 然后使用列表推導來獲取匹配的值


此外,您必須使用axis=1它才能工作:


print(df.apply(lambda x: ' '.join([i for i in x['Col1'].split() if i in x['Col2'].split()]), axis=1))

輸出:


0    the cat

1           

2    chicken

dtype: object

如果你想要NULL,而不僅僅是一個空值,請使用:


print(df.apply(lambda x: ' '.join([i for i in x['Col1'].split() if i in x['Col2'].split()]), axis=1).str.replace('', 'NULL'))

輸出:


0    the cat

1    NULL

2    chicken

dtype: object


查看完整回答
反對 回復 2021-12-29
?
慕娘9325324

TA貢獻1783條經(jīng)驗 獲得超4個贊

這里不需要使用 lambda 函數(shù),只需檢查每個單詞是否包含在同一列的字符串中。zip() 函數(shù)對于列迭代非常有用。這是一種方法:


import pandas as pd


data_frame = pd.DataFrame(

    {'col1':{

        1:'the cat crossed a road',

        2:'the dog barked',

        3:'the chicken barked',},

    'col2':{

        1: 'the cat alligator',

        2: 'some words here',

        3: 'chicken soup'}}

)


# output the overlap as a list

output = [

    [word for word in line1.split() if word in line2.split()] 

    for line1, line2 in zip(data_frame['col1'].values, data_frame['col2'].values)

]


# To add your new values a column

data_frame['col3'] = output


# Or, if desired, keep as a list and remove empty rows 

output = [row for row in output if row]


查看完整回答
反對 回復 2021-12-29
?
慕哥9229398

TA貢獻1877條經(jīng)驗 獲得超6個贊

檢查


l=[' '.join([t for t in x if t in y]) for x, y in zip(df1.Col1.str.split(' '),df2.Col2.str.split(' '))]

pd.DataFrame({'Col3':l})

Out[695]: 

      Col3

0  the cat

1         

2  chicken


查看完整回答
反對 回復 2021-12-29
  • 3 回答
  • 0 關(guān)注
  • 146 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學習伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號