访问 Pandas 列中不规则出现的列表值的第一项

alk*_*key 5 python lambda pandas

我有一个 pandas 数据框,在其中一列中,某些值中出现了列表值。我需要能够提取列表的第一项,如果它是一个列表,如果它不是一个列表,那么该值将保持不变。我正在努力使用 lambda 函数来实现它:

df1 = pd.DataFrame({'Fruits':['Apple',['Banana',6],'Kiwi','Cheese']})

df1['Fruits'] = df1['Fruits'].apply(lambda(x): x[0] if (type(x) == 'list') else x) 
Run Code Online (Sandbox Code Playgroud)

如果我使用上面的内容,该列保持不变。我猜这一定是 lambda 函数中的条件语句有问题......

我也很感兴趣是否有更好的方法在 Pandas 中实现这一目标。

jez*_*ael 4

您可以删除''from'list'list

df1['Fruits'] = df1['Fruits'].apply(lambda  x : x[0] if type(x) == list else x)
print (df1)
   Fruits
0   Apple
1  Banana
2    Kiwi
3  Cheese
Run Code Online (Sandbox Code Playgroud)

类似的解决方案是使用isinstance

df1['Fruits'] = df1['Fruits'].apply(lambda x: x[0] if isinstance(x, list) else x)
print (df1)
   Fruits
0   Apple
1  Banana
2    Kiwi
3  Cheese
Run Code Online (Sandbox Code Playgroud)

或者可以使用list comprehension

df1['Fruits'] = [x[0] if type(x) == list else x for x in df1['Fruits']]
print (df1)
   Fruits
0   Apple
1  Banana
2    Kiwi
3  Cheese
Run Code Online (Sandbox Code Playgroud)