本文介绍了如果在python的数据框中为NaN,则删除单元格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的数据框。

I have a dataframe like this.

   Project 4    Project1    Project2    Project3
0   NaN         laptio          AB      NaN
1   NaN         windows         ten     NaN
0   one         NaN             NaN
1   two         NaN             NaN

我要从项目4列中删除NaN值

I want to delete NaN values from Project 4 column

我想要的输出应该是

df,

   Project 4    Project1    Project2    Project3
0   one         laptio          AB      NaN
1   two         windows         ten     NaN
0                   NaN        NaN       NaN
1                NaN            NaN


推荐答案

如果数据框的索引只是标准的0到n个有序整数,则可以将 Project4 列弹出到系列中,然后将 NaN 值,重置索引,然后将其与数据框合并回去。

If your data frame's index is just standard 0 to n ordered integers, you can pop the Project4 column to a series, drop the NaN values, reset the index, and then merge it back with the data frame.

import pandas a pd

df = pd.DataFrame([[pd.np.nan, 1,2,3],
                   [pd.np.nan, 4,5,6],
                   ['one',7,8,9],
                   ['two',10,11,12]], columns=['p4','p1','p2','p3'])

s = df.pop('p4')
pd.concat([df, ps.dropna().reset_index(drop=True)], axis=1)

# returns:
   p1  p2  p3   p4
0   1   2   3  one
1   4   5   6  two
2   7   8   9  NaN
3  10  11  12  NaN

这篇关于如果在python的数据框中为NaN,则删除单元格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-03 17:10