【发布时间】:2018-06-19 10:45:41
【问题描述】:
我是一名 R 用户,正在学习如何使用 Python 的 dfply,Python 相当于 R 的 dplyr。我的问题:在 dfply 中,我无法屏蔽管道中的多个条件。我寻求涉及 dfply 管道而不是多行子集的解决方案。
我的代码:
# Import
import pandas as pd
import numpy as np
from dfply import *
# Create data frame and mask it
df = pd.DataFrame({'a':[np.nan,2,3,4,5],'b':[6,7,8,9,np.nan],'c':[5,4,3,2,1]})
df2 = (df >>
mask((X.a.isnull()) | ~(X.b.isnull())))
print(df)
print(df2)
这里是原始数据框,df:
a b c
0 NaN 6.0 5
1 2.0 7.0 4
2 3.0 8.0 3
3 4.0 9.0 2
4 5.0 NaN 1
这是管道掩码的结果,df2:
a b c
0 NaN 6.0 5
4 5.0 NaN 1
但是,我希望这样:
a b c
0 NaN 6.0 5
1 2.0 7.0 4
2 3.0 8.0 3
3 4.0 9.0 2
为什么不用“|”和“~”运算符会导致列“a”是either NaN 或列“b”不是 NaN 的行?
对了,我也试过np.logical_or():
df = pd.DataFrame({'a':[np.nan,2,3,4,5],'b':[6,7,8,9,np.nan],'c':[5,4,3,2,1]})
df2 = (df >>
mask(np.logical_or(X.a.isnull(),~X.b.isnull())))
print(df)
print(df2)
但这导致了错误:
mask(np.logical_or(X.a.isnull(),~X.b.isnull())))
ValueError: invalid __array_struct__
【问题讨论】:
标签: python logical-operators dfply