Elasticsearch中的索引熊猫数据框,具有空值但不包含nan

时间:2020-01-19 01:32:05

标签: pandas elasticsearch

我正在对来自Elasticsearch中熊猫数据框的数据建立索引。 我为某些es字段设置了null_value,但没有其他字段。 如何删除不包含null_value的列,而保留那些(将value设置为None)的列?

es映射:

    "properties": {
        "sa_start_date": {"type": "date", "null_value": "1970-01-01T00:00:00+00:00"},
        "location_name": {"type": "text"},

代码:

cols_with_null_value = ['sa_start_date']
orig = [{
    'meter_id': 'M1',
    'sa_start_date': '',
    'location_name': ''
},{
    'meter_id': 'M1',
    'sa_start_date': '',
    'location_name': 'a'
}]
df = pd.DataFrame.from_dict(orig)

df['sa_start_date'] = df['sa_start_date'].apply(pd.to_datetime, utc=True, errors='coerce')
df.replace({'': np.nan}, inplace=True)
df:
   meter_id sa_start_date location_name
0       M1           NaT           NaN
1       M1           NaT             a

elasticsearch索引所需的字典:

{"meter_id": M1, "sa_start_date": None}
{"meter_id": M1, "sa_start_date": None, "location_name": "a"}

请注意,未索引具有NaN的location_name单元,但已为具有NaT的sa_start_date单元建立索引。 我已经尝试了许多事情,每件事都比上一次荒谬。没有什么值得展示的。 任何想法表示赞赏!

对此进行了尝试,但无与NaN一起删除了。

df[null_value_cols] = df[null_value_cols].replace({np.nan: None})
df:
   meter_id sa_start_date location_name
0       M1          None           NaN
1       M1          None             a
for row in df.iterrows():
    ser = row[1]
    ser.dropna(inplace=True)

    lc = {k: v for k, v in dict(row[1]).items()}

lc: {'meter_id': 'M1'}
lc: {'meter_id': 'M1', 'location_name': 'a'}

1 个答案:

答案 0 :(得分:3)

请勿在此处使用.dropna()。它将删除整行或整列;并且您希望保留所有内容,但空位置名称除外。

您可以通过以下方式进行操作:

df.replace({'': None}, inplace=True) # replace with None instead of np.nan

for idx,row in df.iterrows(): 
    lc = {k:v for k,v in row.items() if not (k == 'location_name' and v is None)} 
    print(lc) 

结果:

{'meter_id': 'M1', 'sa_start_date': None}
{'meter_id': 'M1', 'sa_start_date': None, 'location_name': 'a'}