python - 数据框列表,如果行包含特殊字符串,则删除数据框列(列具有不同的名称)
问题描述
我拥有的是数据框列表。
需要注意的重要一点是,数据帧的形状在 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)
有什么建议么。
解决方案
你可以试试:
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)
.
推荐阅读
- python - Selenium 打开 geckdriver 错误:NotADirectoryError: [WinError 267] 目录名无效
- python - 给定 pandas 数据框列,如果 X 是字典中的键,如何将嵌套列表中的元素 X 替换为字典中的值?
- javascript - 在javascript中调用一个函数如何设置另一个函数的变量?
- python - 从 dict 中的数据驱动键获取值
- python - 为什么硒不能正确循环?
- pine-script - 为什么我的 Pine Script Zigzag% 不起作用?
- javascript - 为什么我的 fetch 请求被多次发送?
- google-bigquery - 将相同输入类型的多个值传递给 BigQuery 表值函数
- javascript - 将对象转换为 json 时,有没有办法不包含方法?
- google-apps-script - Google Data Studio 中同一 Google 帐户的不同 API 密钥