dre*_*eab 4 python indexing conditional-statements dataframe pandas
我正在使用熊猫,并希望选择数据子集并将其应用于其他列。例如
我现在使用.isnull()和可以正常工作.notnull()。例如
df = pd.DataFrame({'A' : pd.Series(np.random.randn(4)),
'B' : pd.Series(np.nan),
'C' : pd.Series(['yes','yes','no','maybe'])})
df['D']=''
df
Out[44]:
A B C D
0 0.516752 NaN yes
1 -0.513194 NaN yes
2 0.861617 NaN no
3 -0.026287 NaN maybe
# Now try the first conditional expression
df['D'][df['A'].notnull() & df['B'].isnull()] \
= df['A'][df['A'].notnull() & df['B'].isnull()]
df
Out[46]:
A B C D
0 0.516752 NaN yes 0.516752
1 -0.513194 NaN yes -0.513194
2 0.861617 NaN no 0.861617
3 -0.026287 NaN maybe -0.0262874
Run Code Online (Sandbox Code Playgroud)
当添加第三个条件时,还要检查C列中的数据是否与特定字符串匹配,我们得到以下错误:
df['D'][df['A'].notnull() & df['B'].isnull() & df['C']=='yes'] \
= df['A'][df['A'].notnull() & df['B'].isnull() & df['C']=='yes']
File "C:\Anaconda2\Lib\site-packages\pandas\core\ops.py", line 763, in wrapper
res = na_op(values, other)
File "C:\Anaconda2\Lib\site-packages\pandas\core\ops.py", line 718, in na_op
raise TypeError("invalid type comparison")
TypeError: invalid type comparison
Run Code Online (Sandbox Code Playgroud)
我读到由于不同的数据类型而发生这种情况。如果我将C列中的所有字符串都更改为整数或布尔值,则可以使它工作。我们也知道字符串本身可以工作,例如df['A'][df['B']=='yes']给出一个布尔列表。
那么,有什么想法在条件表达式中组合这些数据类型时如何/为什么不起作用?还有什么更蟒蛇的方法来完成似乎很漫长的事情?
谢谢
小智 7
万一这个解决方案对任何人都行不通,发生在我身上的另一种情况是,即使我以as读取所有数据dtype=str(因此,进行任何字符串比较都应该是可以的[ie df[col] == "some string"]),但我的列全为空,它变为type float,与字符串进行比较时会出现错误。
为了解决这个问题,您可以.astype(str)用来确保将字符串与字符串进行比较。
我认为您需要在条件中添加括号(),也最好用于ix选择带有布尔掩码的列,该布尔掩码可以分配给变量mask:
mask = (df['A'].notnull()) & (df['B'].isnull()) & (df['C']=='yes')
print (mask)
0 True
1 True
2 False
3 False
dtype: bool
df.ix[mask, 'D'] = df.ix[mask, 'A']
print (df)
A B C D
0 -0.681771 NaN yes -0.681771
1 -0.871787 NaN yes -0.871787
2 -0.805301 NaN no
3 1.264103 NaN maybe
Run Code Online (Sandbox Code Playgroud)