我有一个df:
df =
c1 c2 c3 c4 c5
0 K 6 nan Y V
1 H nan g 5 nan
2 U B g Y L
还有一根绳子
s = 'HKg5'
我想返回行,其中s[0]=c1的值,s[1]=c2的值,…+在某些情况下,s[i]=nan
例如,上面df中的第1行与字符串匹配
row 1=
c1 c2 c3 c4 c5
1 H nan g 5 nan
match=True, regardless of s[1,4]=nan
s = H K g 5
而且字符串长度是动态的,所以我的df cols在c10以上
我正在使用df.apply,但我不能清楚地理解它。我想编写一个传递给df.apply的函数,同时传递字符串
谢谢你的帮助
Chris答案的输出
df=
c1 c2 c3 c4 c5
0 K 6 NaN Y V
1 H NaN g 5 NaN
2 U B g Y L
s = 'HKg5'
s1 = pd.Series(list(s), index=[f'c{x+1}' for x in range(len(s))])
df.loc[((df == s1) | (df.isna())).all(1)]
输出
`c1 c2 c3 c4 c5`
从字符串创建一个helper
Series
,并使用布尔逻辑进行筛选:逻辑为
df
等于(==
)。此值或(|
)为nan(isna
)沿轴1使用
all
返回所有值均为True
的行[外]
因此,作为一项功能,您可以:
[外]
更新
我无法用提供的例子再现你的问题。我猜数据帧中的一些值可能有前导/尾随空格
在尝试上述解决方案之前,请尝试以下预处理步骤:
相关问题 更多 >
编程相关推荐