[英]pandas dataframe how to replace None values in a column with list values or remove none values or pd.np.nan
[英]How To Replace Pandas Column NaN Values with Empty List Values?
給定一個json
記錄字符串,其中每條記錄的“模式”不一致(例如,每條記錄都沒有完整的“列”集):
s = """[{"a": 3, "b":[]}, {"a": 4, "b": [4]}, {"a": 5}]"""
可以從這個字符串構造一個 pandas DataFrame
:
import pandas as pd
import json
json_df = pd.DataFrame.from_records(json.loads(s))
這導致
a b
0 3 []
1 4 [4]
2 5 NaN
如何用空list
值填充熊貓Series
列的所有NaN
實例? 預期的結果 DataFrame 將是:
a b
0 3 []
1 4 [4]
2 5 []
我嘗試了以下方法; 沒有一個工作:
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])
預先感謝您的考慮和回應。
首先找到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.