我有一个示例数据:
df1 df2 df3
Dell. 10. [intiated, purchased]
Apple 20. [initiated]
Toshiba. 15. [purchased]
我想根据df3中的值过滤行值。
当值为[初始化,购买]时,df3的示例过滤应返回
df1 df2 df3
Dell. 10. [intiated, purchased]
当值为[initiated]时,df3的示例过滤应返回
df1 df2 df3
Apple. 20. [intiated]
当价值被[购买]时,df3的示例过滤应返回
df1 df2 df3
Toshiba. 15. [purchased]
其他方式:
val=['intiated','purchased']
#the value that you want to find
m=df['df3'].map(lambda x:all(y in val for y in x))
#check the value 'val' is inside your list or not(it will give you boolean series)
通过m
:最终过滤出结果
df[m]
#OR
df.loc[m]
上述代码的输出:
df1 df2 df3
0 Dell 10 [intiated, purchased]
IIUC有一种方法:
df['df3'] = df['df3'].astype(str) # convert to string type if required
req_val = '[initiated]'
filtered_df = df[df['df3'].eq(req_val)] # use boolean indexing to filter
输出:
df1 df2 df3
1 Apple 20.0 [initiated]
完整示例:
df = pd.DataFrame({'df1': {0: 'Dell.', 1: 'Apple', 2: 'Toshiba.'},
'df2': {0: 10.0, 1: 20.0, 2: 15.0},
'df3': {0: '[intiated, purchased]', 1: '[initiated]', 2: '[purchased]'}})
req_val = '[initiated]'
filtered_df = df[df['df3'].eq(req_val)]