【问题标题】:Deleting multiple columns of CSV files based on certain conditions on PythonPython上根据特定条件删除多列CSV文件
【发布时间】:2020-07-24 03:32:59
【问题描述】:

我有一个包含多列(几乎 100 列)的 CSV 文件。如何使用 Python 中的某些条件一次过滤多个列?更准确地说,许多列对我来说毫无用处。如何过滤文件?

PS:我是初学者。

【问题讨论】:

标签: python pandas dataframe


【解决方案1】:

假设您在 csv 文件中有以下内容

Col1、Col2、Col3
1,a,0
2,b,0
3,d,1

使用以下脚本在 pandas 数据框中读取它

import pandas as pd  

df=pd.read_csv(file)

要查看数据框 df 中的列,请使用

print(df.columns)

这将以列表的形式为您提供 df 中的列名,在本例中为 ['col1', 'col2', 'col3']

要仅保留特定列(例如 col1 和 col3),您可以使用

df=df [ [ "col1","col3"] ]

现在,如果您打印 (df.columns),它将只有 ['col1', 'col3']

编辑回复评论:

如果要删除满足特定条件的列,可以使用以下脚本

for column in df.columns:

    if 0 in df[column].values: # This will check if 0 is in values of column,  you can add any condition you want here

    print('Deleting column', column) # I assume you want to delete the column that fulfills the condition

    df=df.drop(columns=column) # This statement will delete the column fulfilling the condition
print("df after deleting columns:")
print(df)

它会打印出来

删除列 col3

删除列后的df:

col1,col2

1,a

2,b

3,c

【讨论】:

  • 我必须检查 col 1,col 2,............,col X 是否满足某些条件。我该怎么做?
  • 我已经编辑了答案,您可以查看脚本如何检查哪些列满足某些条件。如果有帮助,请投票。谢谢
【解决方案2】:

如果您想从数据框列中删除所有零值,您应该按照以下步骤操作,(假设您的数据框名称为 df

  1. 首先将所有零值替换为nan
import numpy as np
import pandas as pd

df = df.replace(0, np.nan)

  1. pandas 中使用dropna 方法删除nan
df = df.dropna(axis=1, how='all')

参数axis=1用于为columnwise分配丢弃规则。 how=all 用于检查此列中的所有值。

这样,单行答案在下面

df = df.replace(0, np.nan).dropna(axis=1, how=all)

【讨论】:

    【解决方案3】:

    例如,如果您有一个数据框 df,其中包含 col1col2col3col4 列,并且您只需要 col1col2,您可以这样做 -

    new_df = df[['col1', 'col2']]
    

    【讨论】:

      【解决方案4】:

      您可以将 csv 文件解析为 pandas 数据框,然后进行播放。请查看有关如何读取 csv 文件的 pandas 文档。您可以根据标题名称提取所需的列。您还可以快速应用数学运算。不过,对于大规模计算,请注意 python 不适合,因为每次导入库时。

      【讨论】:

      • 我有多个值为零的列。我需要删除所有以零为值的列。我在 pandas 文档中没有找到它。
      猜你喜欢
      • 2021-04-28
      • 2020-03-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-01
      • 1970-01-01
      • 2014-03-14
      相关资源
      最近更新 更多