简体   繁体   English

如何用空列表值替换 Pandas 列 NaN 值?

[英]How To Replace Pandas Column NaN Values with Empty List Values?

Given a json string of records where the "schema" for each record is not consistent (eg each record does not have the full set of "columns"):给定一个json记录字符串,其中每条记录的“模式”不一致(例如,每条记录都没有完整的“列”集):

s = """[{"a": 3, "b":[]}, {"a": 4, "b": [4]}, {"a": 5}]"""

A pandas DataFrame can be constructed from this string:可以从这个字符串构造一个 pandas DataFrame

import pandas as pd
import json

json_df = pd.DataFrame.from_records(json.loads(s))

Which results in这导致

   a    b
0  3   []
1  4  [4]
2  5  NaN

How can all NaN instances of a pandas Series column be filled with empty list values?如何用空list值填充熊猫Series列的所有NaN实例? The expected resulting DataFrame would be:预期的结果 DataFrame 将是:

   a    b
0  3   []
1  4  [4]
2  5   []

I have tried the following;我尝试了以下方法; none of which worked:没有一个工作:

json_df[json_df.b.isna()] = [[]]*json_df[json_df.b.isna()].shape[0]

from itertools import repeat
json_df[json_df.b.isna()] = repeat([], json_df[json_df.b.isna()].shape[0])

import numpy as np
json_df[json_df.b.isna()] = np.repeat([], json_df[json_df.b.isna()].shape[0])

Thank you in advance for your consideration and response.预先感谢您的考虑和回应。

first find the nan and replace by the same shape of data首先找到nan并替换为相同形状的数据

json_df.loc[json_df.b.isnull(), 'b'] = json_df.loc[json_df.b.isnull(), 'b'].apply(lambda x: [])


    a   b
0   3   []
1   4   [4]
2   4   []

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 熊猫数据框如何用列表值替换列中的无值或删除无值或 pd.np.nan - pandas dataframe how to replace None values in a column with list values or remove none values or pd.np.nan Pandas:如何根据另一列替换列中的 Nan 值? - Pandas: How to replace values of Nan in column based on another column? 如何使用pandas替换具有不同随机值的列中的每个NaN? - How to replace every NaN in a column with different random values using pandas? 如何在 Pandas 数据框的列中用零替换 NaN 值? - How to replace NaN values by Zeroes in a column of a Pandas Dataframe? Pandas - 如何仅将 dataframe 列中的空字符串值强制为 NaN - Pandas - how to coerce only empty string values in dataframe column to NaN Pandas将NaN值替换为特定列的列表 - Pandas replace NaN values with a list for specific columns 如何用 Pandas 中 4 个元素的空列表 [] 填充数据框 Nan 值? - How to fill dataframe Nan values with empty list [] of 4 elements in pandas? 如何在 pandas 中用空列表 [] 填充 dataframe Nan 值? - How to fill dataframe Nan values with empty list [] in pandas? Pandas Dataframe 用 B 列的值替换 A 列的 NaN 值 - Pandas Dataframe replace NaN values of column A with values from column B 用熊猫数据框中另一列中的值替换空列表 - replace empty list with values in another column in pandas dataframe
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM