从pandas数据fram中删除空值行

2024-06-16 13:20:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图从数据框中删除一行,其中一列的值为空。我所能找到的大部分帮助都与消除迄今为止对我不起作用的NaN值有关。

在这里,我创建了数据帧:

  # successfully crated data frame
 df1 = ut.get_data(symbols, dates) # column heads are 'SPY', 'BBD'

# can't get rid of row containing null val in column BBD
# tried each of these with the others commented out but always had an 
# error or sometimes I was able to get a new column of boolean values
# but i just want to drop the row
df1 = pd.notnull(df1['BBD']) # drops rows with null val, not working
df1 = df1.drop(2010-05-04, axis=0)
df1 = df1[df1.'BBD' != null]
df1 = df1.dropna(subset=['BBD'])
df1 = pd.notnull(df1.BBD)


# I know the date to drop but still wasn't able to drop the row
df1.drop([2015-10-30])
df1.drop(['2015-10-30'])
df1.drop([2015-10-30], axis=0)
df1.drop(['2015-10-30'], axis=0)


with pd.option_context('display.max_row', None):
    print(df1)

以下是我的输出:

Output

有人能告诉我如何删除这一行吗?最好是用空值标识行,以及如何按日期删除行?

我和熊猫一起工作的时间不长,我在这方面已经坚持了一个小时。任何建议都将不胜感激。


Tags: oftheto数据getwithcolumnnull
3条回答

这应该可以做到:

df = df.dropna(how='any',axis=0) 

它将删除其中有“任意”空值的每个(轴=0)。

示例:

#Recreate random DataFrame with Nan values
df = pd.DataFrame(index = pd.date_range('2017-01-01', '2017-01-10', freq='1d'))
# Average speed in miles per hour
df['A'] = np.random.randint(low=198, high=205, size=len(df.index))
df['B'] = np.random.random(size=len(df.index))*2

#Create dummy NaN value on 2 cells
df.iloc[2,1]=None
df.iloc[5,0]=None

print(df)
                A         B
2017-01-01  203.0  1.175224
2017-01-02  199.0  1.338474
2017-01-03  198.0       NaN
2017-01-04  198.0  0.652318
2017-01-05  199.0  1.577577
2017-01-06    NaN  0.234882
2017-01-07  203.0  1.732908
2017-01-08  204.0  1.473146
2017-01-09  198.0  1.109261
2017-01-10  202.0  1.745309

#Delete row with dummy value
df = df.dropna(how='any',axis=0)

print(df)

                A         B
2017-01-01  203.0  1.175224
2017-01-02  199.0  1.338474
2017-01-04  198.0  0.652318
2017-01-05  199.0  1.577577
2017-01-07  203.0  1.732908
2017-01-08  204.0  1.473146
2017-01-09  198.0  1.109261
2017-01-10  202.0  1.745309

有关详细信息,请参见reference

如果您的数据帧一切正常,那么删除nan就应该如此简单。如果仍然不起作用,请确保为列定义了正确的数据类型(pd.to_numeric浮现在脑海中…)

您的列中的值似乎是“null”,而不是真正的NaN,这就是dropna的含义。所以我会尝试:

df[df.BBD != 'null']

或者,如果值实际上是NaN

df[pd.notnull(df.BBD)]

----清除空所有列---

df = df.dropna(how='any',axis=0)

---如果要根据1列清除空值--

df[~df['B'].isnull()]

                A         B
2017-01-01  203.0  1.175224
2017-01-02  199.0  1.338474
                              **2017-01-03  198.0       NaN** clean
2017-01-04  198.0  0.652318
2017-01-05  199.0  1.577577
2017-01-06    NaN  0.234882
2017-01-07  203.0  1.732908
2017-01-08  204.0  1.473146
2017-01-09  198.0  1.109261
2017-01-10  202.0  1.745309

请原谅任何错误。

相关问题 更多 >