使用 isin 对 python 数据帧进行切片

Slicing python dataframe with isin

我正在尝试一些我认为很简单的事情,但是我总是收到错误,我不知道为什么。

我正在尝试在 df2 的新列中设置一个值。如果值是来自 df2 的列匹配来自 df1 “col”的任何值,则写入“结果”,否则为“无结果”。

#Create a series from df column 
series_from_df = df1['Col']
df2['new_col'] = 'result' if df2['Col1'].isin(series_from_df) else 'Not result'

上面给我一个错误:

(<class 'ValueError'>, ValueError('The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().'), <traceback object at 0x7f9081a28f80>)

然后我尝试在下面为 series_from_df

添加方形制动器
#Create a series from df column 
series_from_df = df1['Col']
df2['new_col'] = 'result' if df2['Col1'].isin([series_from_df]) else 'Not result'

我得到了和以前一样的错误。

我错过了什么?

df2['Col1'].isin(df1['Col1']) 是一个布尔系列,但您正试图将其用作 if 中的条件,这需要 truth-value。您可以使用 numpy.where 而不是 isin 创建的系列用作条件:

df2['new_col'] = np.where(df2['Col1'].isin(df1['Col1']), 'result', 'Not result')

您也可以使用map来替换布尔值:

df2['new_col'] = \
    df2['Col1'].isin(df1['Col']).replace({True: 'result', False: 'Not Result'})
print(df2)

# Output
   Col1     new_col
0     1      result
1     2      result
2     3  Not Result
3     4      result
4     5      result

设置:

df1 = pd.DataFrame({'Col': [1, 2, 4, 5]})
df2 = pd.DataFrame({'Col1': [1, 2, 3, 4, 5]})