检查列表是否包含 None 个值,如果它包含其他值,则替换为其他值
Checking if a list contains None values if it contains other values, substitute by other value
所以我有这样的数据集
UserId
CampaignSource
Potato
'hello','hello','hello',None
Carrot
'hello','hello','hello',None
Carrot2
None,None,None,None
Potato2
'kawai','kawai','kawai','kawai',None
基本上我想做的是检查列表是否包含 None 个值。并将每个 None 值替换为“hello”字符串。但要确保 None 填充列表未填充。
UserId
CampaignSource
Potato
'hello','hello','hello','hello'
Carrot
'hello','hello','hello','hello'
Carrot2
None,None,None,None
Potato2
'kawai','kawai','kawai','kawai','kawai'
有没有其他方法来解决这个问题?顺便说一句,无法显示为堆栈上奇怪错误的 bcs 列表
for lst in df_safe_l['CampaignSource']:
if None in lst:
for j in set(lst):
if j:
lst[:] = [j] * len(lst)
我的工作正常,但我正在寻找更快的替代品
首先使用None in set(x) and len(set(x)) == 1
检查列表是否仅包含None
。如果是,那么您不需要更换任何东西。但如果它包含 None
以外的任何内容,则创建一个包含类型字符串 len(x)
次的新列表。尝试使用 .apply()
。 :
df_safe_l['CampaignSource'] = df_safe_l['CampaignSource'].apply(lambda x: x if None in set(x) and len(set(x)) == 1 else [[i for i in x if isinstance(i, str)][0]] * len(x))
输出:
userid CampaignSource
0 Potato [hello, hello, hello, hello]
1 Carrot [hello, hello, hello, hello]
2 Carrot2 [None, None, None, None]
3 Potato2 [kawai, kawai, kawai, kawai, kawai]
您可以尝试将列表转为 Series,然后用其他值填充 None
df['CampaignSource'] = df['CampaignSource'].apply(lambda lst: pd.Series(lst).bfill().ffill().tolist())
print(df)
UserId CampaignSource
0 Potato [hello, hello, hello, hello]
1 Carrot [hello, hello, hello, hello]
2 Carrot2 [None, None, None, None]
3 Potato2 [kawai, kawai, kawai, kawai, kawai]
所以我有这样的数据集
UserId | CampaignSource |
---|---|
Potato | 'hello','hello','hello',None |
Carrot | 'hello','hello','hello',None |
Carrot2 | None,None,None,None |
Potato2 | 'kawai','kawai','kawai','kawai',None |
基本上我想做的是检查列表是否包含 None 个值。并将每个 None 值替换为“hello”字符串。但要确保 None 填充列表未填充。
UserId | CampaignSource |
---|---|
Potato | 'hello','hello','hello','hello' |
Carrot | 'hello','hello','hello','hello' |
Carrot2 | None,None,None,None |
Potato2 | 'kawai','kawai','kawai','kawai','kawai' |
有没有其他方法来解决这个问题?顺便说一句,无法显示为堆栈上奇怪错误的 bcs 列表
for lst in df_safe_l['CampaignSource']:
if None in lst:
for j in set(lst):
if j:
lst[:] = [j] * len(lst)
我的工作正常,但我正在寻找更快的替代品
首先使用None in set(x) and len(set(x)) == 1
检查列表是否仅包含None
。如果是,那么您不需要更换任何东西。但如果它包含 None
以外的任何内容,则创建一个包含类型字符串 len(x)
次的新列表。尝试使用 .apply()
。 :
df_safe_l['CampaignSource'] = df_safe_l['CampaignSource'].apply(lambda x: x if None in set(x) and len(set(x)) == 1 else [[i for i in x if isinstance(i, str)][0]] * len(x))
输出:
userid CampaignSource
0 Potato [hello, hello, hello, hello]
1 Carrot [hello, hello, hello, hello]
2 Carrot2 [None, None, None, None]
3 Potato2 [kawai, kawai, kawai, kawai, kawai]
您可以尝试将列表转为 Series,然后用其他值填充 None
df['CampaignSource'] = df['CampaignSource'].apply(lambda lst: pd.Series(lst).bfill().ffill().tolist())
print(df)
UserId CampaignSource
0 Potato [hello, hello, hello, hello]
1 Carrot [hello, hello, hello, hello]
2 Carrot2 [None, None, None, None]
3 Potato2 [kawai, kawai, kawai, kawai, kawai]