在我的数据框中,我需要删除包含特定字符的列。为了搜索这些列,我尝试在 python 中编写一个 for 循环来迭代每一列,如果找到包含不需要的字符的列,则必须删除该列。 我的数据框如下所示,我需要删除具有“f”和“t”的 col3 和 col5
col1 col2 col3 col4 col5 col6
1245 pink f Mar f f
245 green f Feb t f
1237 grey t Apr f f
267 black f Sep t f
我正在尝试编写一个与此类似的脚本
for col in df.items():
if df[col] == 'f'
df = df.drop([col], axis=1)
最佳答案
您可以创建仅包含 f
的列的 bool 掩码,然后将该掩码应用于 df:
mask = ((df == 'f') | (df=='t')).all(0)
df = df[df.columns[~mask]]
如果您想离开第 6 列,您可以这样做:
mask0 = ((df == 'f') | (df == 't')).all(0)
mask1 = (df == 'f').all(0)
df0 = df[df.columns[~mask0]]
df1 = df[df.columns[mask1]]
df = pd.concat([df0, df1], axis=1)
关于python - 通过迭代列来搜索列中的元素,pandas,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51221851/