[英]pandas dataframe how to replace None values in a column with list values or remove none values or pd.np.nan
data = {
'list_id' : [[50, None],[20, 68],[10, 7],[73, 4, 26, 3],[50, None],[68, 20, 61, 62],[68, None]]
}
df = pd.DataFrame.from_dict(data)
print (df)
I tried the below steps,我尝试了以下步骤,
expected Output预期输出
data = {
'list_id' : [[50],[20, 68],[10, 7],[73, 4, 26, 3],[50],[68, 20, 61, 62],[68]]
}
df = pd.DataFrame.from_dict(data)
print (df)
list_id
0 [50]
1 [20, 68]
2 [10, 7]
3 [73, 4, 26, 3]
4 [50]
5 [68, 20, 61, 62]
6 [68]
df[['list_id']] = df['list_id'].apply(lambda el: [ f'' if x is None else x for x in el])
df[['list_id']] = df['list_id'].apply(lambda el: [ f'' if x is None for x in el])
Need to replace None values in column with list elements, either as an empty '' string or None being removed, not sure about np.nan..需要用列表元素替换列中的 None 值,作为空的 '' 字符串或 None 被删除,不确定 np.nan ..
For remove None
or NaN
s values use notna
in list comprehension:要删除None
或NaN
的值, notna
在列表理解中使用notna
:
df['list_id'] = df['list_id'].apply(lambda el: [x for x in el if pd.notna(x)])
print (df)
list_id
0 [50]
1 [20, 68]
2 [10, 7]
3 [73, 4, 26, 3]
4 [50]
5 [68, 20, 61, 62]
6 [68]
For remove only None
s compare by None
with not
:对于仅删除None
s 比较None
与not
:
df['list_id'] = df['list_id'].apply(lambda el: [x for x in el if x is not None])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.