Python 基于条件的新列值
我有一个这样的数据集Python 基于条件的新列值,python,pandas,dataframe,Python,Pandas,Dataframe,我有一个这样的数据集 df = pd.DataFrame({"A" :[1,1,3,4], "B": [1,3,2,2]}) 如果a=1&B=1,3,我想创建一个类型为1的新列,它是C 我使用了.loc,我的代码是 df.loc[(df['A'] == 1)&(df['B'] == 1), 'C'] = 'type 1' df.loc[(df['A'] == 1)&(df['B'] == 3), 'C'] = 'type 1' 以上是工
df = pd.DataFrame({"A" :[1,1,3,4], "B": [1,3,2,2]})
如果a=1&B=1,3,我想创建一个类型为1的新列,它是C
我使用了.loc,我的代码是
df.loc[(df['A'] == 1)&(df['B'] == 1), 'C'] = 'type 1'
df.loc[(df['A'] == 1)&(df['B'] == 3), 'C'] = 'type 1'
以上是工作,但当我使用
df.loc[(df['A'] == 1)&(df['B'] == (1,3)), 'C'] = 'type 1'
不会发生任何事情,它不会显示错误,列也不会更新
预期产量为
A B C
1 1 type 1
1 3 type 1
3 2 Nan
4 2 Nan
还有别的办法吗
提前感谢使用:
使用:
其他方法可能是尝试使用类似于: 如果您想修复代码,您可以尝试使用|分隔:
其他方法可能是尝试使用类似于: 如果您想修复代码,您可以尝试使用|分隔:
以下是一个可能的解决方案,它不使用任何库,而是使用熊猫:
df['C'] = pd.Series(index=range(len(df)), dtype='float')
df['C'][df['A'] == 1 & df['B'].isin((1, 3))] = 'type 1'
以下是一个可能的解决方案,它不使用任何库,而是使用熊猫:
df['C'] = pd.Series(index=range(len(df)), dtype='float')
df['C'][df['A'] == 1 & df['B'].isin((1, 3))] = 'type 1'
df['B'].isin[1,3]not==1,3.==1,3检查该值是否等价于值为1和3的元组。df['B'].isin[1,3]not==1,3.==1,3检查该值是否等价于值为1和3的元组。
df.loc[(df['A'] == 1)&((df['B'] ==1) | (df['B'] ==3)), 'C'] = 'type 1'
df['C'] = pd.Series(index=range(len(df)), dtype='float')
df['C'][df['A'] == 1 & df['B'].isin((1, 3))] = 'type 1'