如果在python中的Dataframe中是NaN,则删除单元格

时间:2017-07-31 10:48:18

标签: python pandas dataframe data-analysis

我有一个像这样的数据框。

$a = [
'first' => '1st',
'second' => '2nd',
'third' => '3rd'
];

pull_by_key( $a, 'second' );
function pull_by_key( &$array, $key ){
   $retval = $array[$key];
   unset( $array[$key] );
   return $retval;
}
echo "<pre>"; print_r($a); die;

我想从Project 4列中删除NaN值

我想要的输出应该是,

df,则

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

1 个答案:

答案 0 :(得分:2)

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

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