首页 > 解决方案 > 数据框列表,如果行包含特殊字符串,则删除数据框列(列具有不同的名称)

问题描述

我拥有的是数据框列表。

需要注意的重要一点是,数据帧的形状在 2-7 列之间有所不同,列的名称也在列的 0 和 len 之间(例如 df1 有 5 列,名称分别为 0、1、2、3、4 等。 df2有 4 列名为 0,1,2,3)

我想检查一列中的一行是否包含某个字符串,然后删除该列。

list_dfs1=[df1,df2,df3...df100]

到目前为止我所做的是以下&我得到一个错误,即第 5 列不在轴上(它存在于某些 DF 中)

for i, df in enumerate(list_dfs1):
    for index,row in df.iterrows():
        if np.where(row.str.contains("DEC")):
            df.drop(index, axis=1)

有什么建议么。

标签: pythonpandas

解决方案


你可以试试:

for df in list_dfs:
    for col in df.columns:
        # If you are unsure about column types, cast column as string:
        df[col] = df[col].astype(str)
        # Check if the column contains the string of interest
        if df[col].str.contains("DEC").any():
            df.drop(columns=[col], inplace=True)

如果您知道所有列都是字符串类型,那么您实际上不必执行df[col] = df[col].astype(str).


推荐阅读