根据python中其他两个字符串列应用的条件创建一个新列

2024-09-28 03:14:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下格式的数据:

pastLocation | currentLocation    
delhi        | bangalore          
delhi        | london,pune,delhi  
mumbai       | mumbai             
pune         | pune, noida       

我必须创建一个名为changeInLocation的新列,如果pastLocation出现在currentLocation中,那么新列的值将是0否则1。 例如,在第二行中,pastLocation即德里出现在相应的currentLocation中,因此changeInLocation的值应该是0

输出格式如下:

pastLocation | currentLocation   | changeInLocation
delhi        | bangalore         | 1
delhi        | london,pune,delhi | 0
mumbai       | mumbai            | 0
pune         | pune, noida       | 0

Tags: 数据格式londondelhimumbaipunebangalorecurrentlocation
3条回答

耶斯雷尔的类似解决方案(无论如何更完整),但没有铸造:

df['changeInLocation']=df.apply(lambda x: 1 if x['pastLocation'] in x['currentLocation'] else 0, axis=1)

与jezrael的解决方案类似,但要注意删除空格并使用set来提高性能:

import pandas as pd

df = pd.DataFrame({'pastLocation': ['delhi', 'delhi', 'mumbai', 'pune'],
                   'currentLocation': ['bangalore', 'london,pune,delhi',
                                       'mumbai', 'pune, noida']})

sets = [{i.strip() for i in row} for row in df['currentLocation'].str.split(',').values]

df['changeInLocation'] = [int(past not in current) for past, current in \
                          zip(df['pastLocation'], sets)]

print(df)

     currentLocation pastLocation  changeInLocation
0          bangalore        delhi                 1
1  london,pune,delhi        delhi                 0
2             mumbai       mumbai                 0
3        pune, noida         pune                 0

使用applyin检查成员身份,然后强制转换为int

df['changeInLocation'] = df.apply(lambda x: x['pastLocation'] not in x['currentLocation'], axis=1).astype(int)

另一个解决方案是压缩列并使用list comprehension

df['changeInLocation'] = [int(a not in b) for a, b in zip(df['pastLocation'], df['currentLocation'])]

print (df)
  pastLocation    currentLocation  changeInLocation
0        delhi          bangalore                 1
1        delhi  london,pune,delhi                 0
2       mumbai             mumbai                 0
3         pune        pune, noida                 0

相关问题 更多 >

    热门问题