Np.where 一直给我很多错误,所以我正在寻找 df.loc 的解决方案。
这是我遇到的 np.where 错误:
C:\Users\xxx\AppData\Local\Continuum\Anaconda2\lib\site-packages\ipykernel\__main__.py:1: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead
See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
if __name__ == '__main__':
我正在使用以下数据框 df:
df = pd.DataFrame({'Column_A': ['AAA','AAA','ABC','CDE'],'checked': ['0','0','1','0'],'duplicate': ['True','True','False','False']})
Column_A checked duplicate
0 AAA 0 True
1 AAA 0 True
2 ABC 1 False
3 CDE 0 False
我想创建一个额外的标志,如果检查为 0 且重复为 True。
我试过了,没用:
df['flag'] = (np.where((df['checked'] == 'Y') &(df['duplicate'] == 'True'), 'Y', '0'))
TypeError: invalid type comparison
我用 df.loc 试了一下:
df['flag'] = (df.loc[df['checked'] == 'Y']& df.loc[df['duplicate'] == 'True'], 'Y','0')
TypeError: invalid type comparison
我得到了同样的错误!
最佳答案
我认为你的 boolean
不是 string
,所以需要删除 '
:
df = pd.DataFrame({'Column_A': ['AAA','AAA','ABC','CDE'],
'checked': ['0','0','1','0'],
'duplicate': [True, True, False, False]})
df['flag'] = np.where((df['checked'] == 'Y') &(df['duplicate'] == True), 'Y', '0')
print (df)
Column_A checked duplicate flag
0 AAA 0 True 0
1 AAA 0 True 0
2 ABC 1 False 0
3 CDE 0 False 0
或者如果与boolean
列比较,== True
可以省略:
df['flag'] = np.where((df['checked'] == 'Y') &(df['duplicate']), 'Y', '0')
print (df)
Column_A checked duplicate flag
0 AAA 0 True 0
1 AAA 0 True 0
2 ABC 1 False 0
3 CDE 0 False 0
如果需要检查 checked
需要 '
因为 strings
:
df['flag'] = np.where((df['checked'] == '0') &(df['duplicate'] == True), 'Y', '0')
print (df)
Column_A checked duplicate flag
0 AAA 0 True Y
1 AAA 0 True Y
2 ABC 1 False 0
3 CDE 0 False 0
编辑:
解决方案 loc
:
df['flag'] = '0'
mask = (df['checked'] == '0') &(df['duplicate'])
df.loc[mask, 'flag'] = 'Y'
print (df)
Column_A checked duplicate flag
0 AAA 0 True Y
1 AAA 0 True Y
2 ABC 1 False 0
3 CDE 0 False 0
关于python:具有多个条件的 pandas np.where 与 df.loc,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44569879/