python - 根据列值删除数据框中的行

标签 python pandas dataframe

我需要删除 C 列中具有空值的所有行。代码如下:

infile="C:\****"

df=pd.read_csv(infile)    

A   B   C   D
1   1   NaN 3
2   3   7   NaN
4   5   NaN 8
5   NaN 4   9
NaN 1   2   NaN

我尝试过两种基本方法。

方法一: 来源:How to drop rows of Pandas DataFrame whose value in certain columns is NaN

df.dropna()

结果是一个空数据帧,这是有道理的,因为每行都有一个 NaN 值。

df.dropna(subset=[3])

对于此方法,我尝试使用列索引号和列名称来处理子集值。数据框仍然是空的。

方法2: 来源:Deleting DataFrame row in Pandas based on column value

df = df[df.C.notnull()]

仍然会产生空数据框!

我做错了什么?

最佳答案

df = pd.DataFrame([[1,1,np.nan,3],[2,3,7,np.nan],[4,5,np.nan,8],[5,np.nan,4,9],[np.nan,1,2,np.nan]], columns = ['A','B','C','D'])
df = df[df['C'].notnull()]
df

关于python - 根据列值删除数据框中的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36848928/

相关文章:

python - Pyro4,使用构造函数参数服务对象。如何?

python - 将特定于组的功能添加到 pandas 数据框

excel - 如何在 Scala/Spark 中从多个 DataFrame 创建包含多个工作表的 Excel 文件?

dataframe - Azure Blob 存储 - 如何读取源字符串 : wasbs://training@dbtrainsouthcentralus. blob.core.windows.net

python - 将 CSV 文件注释行保留在 pandas 中?

python - 沿 2 个轴的 numpy `take`

c# - 愚弄 System.Diagnostics.Process WaitForExit()

python - 如何使 pandas dataframe str.contains 搜索更快

Python pandas 两个表匹配以查找最新日期

r - 基于R中的多个因素确定多个变量的频率