pandas 使用python删除两列中具有多个值的行[已关闭]

qqrboqgw  于 2022-12-16  发布在  Python
关注(0)|答案(4)|浏览(139)

已关闭。此问题需要details or clarity。当前不接受答案。
**想要改进此问题?**添加详细信息并通过editing this post阐明问题。

20小时前关门了。
Improve this question
假设
| 色谱柱_A|色谱柱_B|
| - ---------------------------------------------------|- ------|
| A类|CT|
| A类|T型|
| 附件|T型|
我想从两列中删除两行,这两列包含多个字符,例如(ATT和CT)行,并且只计算剩余的行。请指导我如何使用python编写代码。
预期产出
| 色谱柱_A|色谱柱_B|
| - ------|- ------|
| A类|T型|

luaexgnf

luaexgnf1#

你可以使用lambda函数来遍历每一行并检查是否为true show
代码:

df[df.apply(lambda x: len(x.ColA)<=1 and len(x.ColB)<=1, axis=1)]

通过将列表转换为字符串并仅选择少于2个

df[df.T.apply(lambda x: len(''.join(x))<3)] #len(AT)<3
8i9zcol2

8i9zcol22#

一种使用numpy.char.str_len的方法是:

mask = (np.char.str_len(df.to_numpy("str")) <= 1).all(1)
res = df[mask]
print(res)

产出

Column_A Column_B
1        A        T

第一步:

(np.char.str_len(df.to_numpy("str")) <= 1)

创建布尔矩阵:

[[ True False]
 [ True  True]
 [False  True]]

函数all从该矩阵中找到行,其中所有值都是True

mlmc2os5

mlmc2os53#

您可以使用pandas.DataFrame.applymap并计算每列中每个项目的长度。

m = (df.applymap(len) <= 1).all(axis=1)
print(df[m])

输出:

Column_A   Column_B
1         A          T

说明:

>>> df.applymap(len)

   Column_A   Column_B
0         1          2
1         1          1
2         3          1
dced5bon

dced5bon4#

df[df.apply(lambda x: len("".join(x)) == len(x), axis=1)]

相关问题