Python 将列表列转换为熊猫中的字符串

Python 将列表列转换为熊猫中的字符串,python,pandas,Python,Pandas,我有一个df,叫做df,就像这样。标记位置是字符串或列表。但我希望它们都是字符串。我该怎么做?我还想删除结尾处的空白 输入 预期产量 id tag_positions 1 center 2 right 3 left 4 center 5 left 6 right 7 left 尝试使用strchain和np.where df['tag_positions'] = np.where(df['tag_positions'].map(lambda x : type(x

我有一个df,叫做
df
,就像这样。标记位置是字符串或列表。但我希望它们都是字符串。我该怎么做?我还想删除结尾处的空白

输入

预期产量

id  tag_positions
1   center
2   right
3   left
4   center
5   left
6   right
7   left


尝试使用
str
chain和
np.where

df['tag_positions'] = np.where(df['tag_positions'].map(lambda x : type(x).__name__)=='list',df['tag_positions'].str[0],df['tag_positions'])
也是我最喜欢的
explode

df = df.explode('tag_positions')

您可以使用
apply
并检查
项是否是
列表的实例,如果是,则取第一个元素。然后你可以用
str.strip
去掉不需要的空格

df['tag_positions'].apply(lambda x:x[0],如果是instance(x,list)或else x.str.strip()
输出

Out[42]:
0中心
1对
2左
3中心
4左
5对
6左
名称:0,数据类型:对象
您可以加入:

df['tag_positions'].map(''.join)
或:


您可以
分解
,然后
剥离

df.tag_positions = df.tag_positions.explode().str.strip()
得到

   id tag_positions
0   1        center
1   2         right
2   3          left
3   4        center
4   5          left
5   6         right
6   7          left

您可以像这样使用apply方法进行转换

df.tag_positions = df.tag_positions.apply(lambda x : ''.join(x) if type(x) == list else x)
如果所有列表的长度均为1,则也可以执行以下操作:

df.tag_positions = df.tag_positions.apply(lambda x : x[0] if type(x) == list else x)

这不适用于那些不是list@Eisen啊,好的,请看更新
df.tag_positions = df.tag_positions.apply(lambda x : ''.join(x) if type(x) == list else x)
df.tag_positions = df.tag_positions.apply(lambda x : x[0] if type(x) == list else x)