python dataframe to_dict by index,不包括NaN

时间:2018-03-14 04:33:22

标签: python-2.7 pandas dictionary dataframe nan

samp dataframe

     v1 v2  v3  v4  v5  v6
index                                                                   
0   -2  -2  -2  NaN -2  -2
1   -2  -2  -2  NaN -2  -2
2   -2  -2  -2  NaN -2  -2
3   -2  -2  -2  -2  -2  -2
4   -2  -2  -2  NaN -2  -2

我试图将数据框架更改为字典 我想忽略json文档中的'nan'字段

尝试的是什么:

import pandas as pd
pd.DataFrame((samp.to_dict('index')).items())

期望的输出:

index    values
0   {'v1':'-2', 'v2':'-2','v3':'-2','v5':'-2','v6':'-2'}
1   {'v1':'-2', 'v2':'-2','v3':'-2','v5':'-2','v6':'-2'}
2   {'v1':'-2', 'v2':'-2','v3':'-2','v5':'-2','v6':'-2'}
3   {'v1':'-2', 'v2':'-2','v3':'-2','v4':'-2','v5':'-2','v6':'-2'}
4   {'v1':'-2', 'v2':'-2','v3':'-2','v5':'-2','v6':'-2'}

1 个答案:

答案 0 :(得分:2)

使用df.apply(lambda x : x.dropna().to_dict(),axis=1) Out[362]: index 0 {'v3': -2.0, 'v5': -2.0, 'v6': -2.0, 'v1': -2.... 1 {'v3': -2.0, 'v5': -2.0, 'v6': -2.0, 'v1': -2.... 2 {'v3': -2.0, 'v5': -2.0, 'v6': -2.0, 'v1': -2.... 3 {'v4': -2.0, 'v3': -2.0, 'v5': -2.0, 'v2': -2.... 4 {'v3': -2.0, 'v5': -2.0, 'v6': -2.0, 'v1': -2.... dtype: object

执行此操作
// instantiate a loader
var loader = new THREE.OBJLoader();

// load a resource
loader.load(
  // resource URL
  'models/monster.obj',
  // called when resource is loaded
  function ( object ) {

    scene.add( object );

  },
  // called when loading is in progresses
  function ( xhr ) {

    console.log( ( xhr.loaded / xhr.total * 100 ) + '% loaded' );

  },
  // called when loading has errors
  function ( error ) {

    console.log( 'An error happened' );

  }
);