【发布时间】:2020-07-24 03:32:59
【问题描述】:
我有一个包含多列(几乎 100 列)的 CSV 文件。如何使用 Python 中的某些条件一次过滤多个列?更准确地说,许多列对我来说毫无用处。如何过滤文件?
PS:我是初学者。
【问题讨论】:
-
请始终提供示例输入和预期输出。
-
@MayankPorwal,您发送的问题是关于过滤行的,而发布的问题是关于过滤列的
我有一个包含多列(几乎 100 列)的 CSV 文件。如何使用 Python 中的某些条件一次过滤多个列?更准确地说,许多列对我来说毫无用处。如何过滤文件?
PS:我是初学者。
【问题讨论】:
假设您在 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
【讨论】:
如果您想从数据框列中删除所有零值,您应该按照以下步骤操作,(假设您的数据框名称为 df)
nan
import numpy as np
import pandas as pd
df = df.replace(0, np.nan)
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)
【讨论】:
例如,如果您有一个数据框 df,其中包含 col1、col2、col3 和 col4 列,并且您只需要 col1 和 col2,您可以这样做 -
new_df = df[['col1', 'col2']]
【讨论】:
您可以将 csv 文件解析为 pandas 数据框,然后进行播放。请查看有关如何读取 csv 文件的 pandas 文档。您可以根据标题名称提取所需的列。您还可以快速应用数学运算。不过,对于大规模计算,请注意 python 不适合,因为每次导入库时。
【讨论】: