我有一个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)
如果我使用上面的列保持不变.我猜这个必须是lambda函数中的条件语句的问题….
如果有更好的方法在熊猫中实现这一点,我也会感兴趣.
解决方法:
您可以从列表中删除”列表:
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
类似的解决方案是使用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
或者可以使用列表理解:
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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。