从 pandas 数据框中删除具有空值的行

2024-04-10

我正在尝试从数据框中删除一行,其中其中一列的值为空。我能找到的大部分帮助都与删除 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)

这是我的输出:

有人可以告诉我如何删除该行,最好通过空值识别该行以及如何按日期删除?

我与熊猫一起工作的时间不长,而且我已经在这个问题上停留了一个小时了。任何建议将不胜感激。


这应该完成工作:

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

它将抹掉每一个row(轴=0)有“any“ 其中的值为零。

EXAMPLE:

#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

See the 参考 https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.dropna.html了解更多详情。

如果您的 DataFrame 一切正常,那么删除 NaN 应该就是这么简单。如果这仍然不起作用,请确保为您的列定义了正确的数据类型(pd.转数字 https://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_numeric.html我想到了...)

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

从 pandas 数据框中删除具有空值的行 的相关文章

随机推荐