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

时间:2021-04-27 15:12:03

标签: python pandas

我有一个名为 df 的 df,就像这样。 tag_position 是字符串或列表。但我希望它们都是字符串。我怎样才能做到这一点?我也想去掉末尾的空格。

输入

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

预期输出

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

5 个答案:

答案 0 :(得分:5)

您可以explode然后strip

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

答案 1 :(得分:3)

您可以加入:

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

或者:

df['tag_positions'].str.join('')

答案 2 :(得分:1)

尝试使用带有 strnp.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')

答案 3 :(得分:1)

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

df['tag_positions'].apply(lambda x: x[0] if isinstance(x, list) else x).str.strip()

输出

Out[42]: 
0    center
1     right
2      left
3    center
4      left
5     right
6      left
Name: 0, dtype: object

答案 4 :(得分:1)

你可以像这样使用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)