pandas 将panda列中混合类型的所有值转换为数组类型

xzlaal3s  于 2023-02-14  发布在  其他
关注(0)|答案(1)|浏览(187)

我有一个混合类型的panda Dataframe 列,如下所示

[], 'Traditional', ['Courtyard'], ['Contemporary', 'Florida', 'Patio']

我希望将字符串字段括在[]中

[], ['Traditional'], ['Courtyard'], ['Contemporary', 'Florida', 'Patio']

尝试:

new_col = df['architectural_style']

new_col = [ [x] if (type(x) == 'str') else x for x in new_col ]

但我得到了以下错误:

pyarrow.lib.ArrowInvalid: ('cannot mix list and non-list, non-null values', 'Conversion failed for column ARCHITECTURAL_STYLE with type object')
8fsztsew

8fsztsew1#

代码中的问题是混合维度,type(x)=='str'应该更改为type(x)==str,这必须有效。
或者您可以使用isinstance. e.x

test = [[], 'Traditional', ['Courtyard'], ['Contemporary', 'Florida', 'Patio']]

new_col = [ [x] if isinstance(x,str) else x for x in test]
print(new_col)

这就是你想要的

[[], ['Traditional'], ['Courtyard'], ['Contemporary', 'Florida', 'Patio']]

相关问题