在Python中使用ma numpy中的fiil_value用Null或None值替换掩码值(-) [英] Replacing masked values (--) with a Null or None value using fiil_value from ma numpy in Python

查看:221
本文介绍了在Python中使用ma numpy中的fiil_value用Null或None值替换掩码值(-)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种方法可以将numpy掩码数组中的掩码值替换为null或None值?这是我尝试过的方法,但不起作用.

Is there a way to replace a masked value in a numpy masked array as a null or None value? This is what I have tried but does not work.

for stars in range(length_masterlist_final):
    ....
    star = customSimbad.query_object(star_names[stars])
        #obtain stellar info.
        photometry_dataframe.iloc[stars,0] = star_IDs[stars]
        photometry_dataframe.iloc[stars,1] = star_names[stars]

        photometry_dataframe.iloc[stars,2] = star['FLUX_U'][0]
        #Replace "--" masked values with a Null (i.e., '') value.
        photometry_dataframe.iloc[stars,2] = ma.filled(photometry_dataframe.iloc[stars,2], fill_value=None)
.....
photometry_dataframe.to_csv(output_dir + "simbad_photometry.csv", index=False, header=True, na_rep='NaN')

具体地

(photometry_dataframe.iloc[stars,2] = ma.filled(photometry_dataframe.iloc[stars,2], fill_value=None)) 

产生

'MaskedConstant' object has no attribute '_fill_value'

当我将数据帧输出为csv文件时,我想用''替换掩码值'-'.一种解决方法是将输出的csv文件读回到python并将'-'替换为'',但这是一个可怕的解决方案.必须有一个更好的解决方案.我不希望在csv文件中将掩码值打印为-".

I want to replace masked values '--' with '' when I output the dataframe as a csv file. One work around is to read the outputted csv file back into python and replace '--' with '', but this is a horrible solution. There must be a better solution. I don't want masked values printed as '--' in the csv file.

推荐答案

使用熵:

>>> from pandas import DataFrame
>>> from astropy.table import Table
>>> import numpy as np
>>> 
>>> df = DataFrame()
>>> df['a'] = [1, np.nan, 2]
>>> df['b'] = [3, 4, np.nan]
>>> df
    a   b
0   1   3
1 NaN   4
2   2 NaN
>>> t = Table.from_pandas(df)
>>> t
<Table masked=True length=3>
   a       b   
float64 float64
------- -------
    1.0     3.0
     --     4.0
    2.0      --
>>> t.write('photometry.csv', format='ascii.csv')
>>> 
(astropy)neptune$ cat photometry.csv 
a,b
1.0,3.0
,4.0
2.0,

您可以使用fill_values参数( 查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆