【问题标题】:Convert only rows that list length equals 1 to string仅将列表长度等于 1 的行转换为字符串
【发布时间】:2020-03-04 08:41:42
【问题描述】:

我在 Python 中有一个 DataFrame,其中 tags 列中的每一行都是一个列表:

df
>>>  name          tags
>>>  alice   |      [a]
>>>  bruce   |   [a, b, c]

我只想将具有列表length = 1 的行转换为字符串。 预期结果

df
>>>  name          tags
>>>  alice   |       a
>>>  bruce   |   [a, b, c]

【问题讨论】:

    标签: python string pandas list


    【解决方案1】:

    你可以使用:

    c=df['tags'].str.len().eq(1)
    df['tags']=np.where(c,df['tags'].str[0],df['tags'])
    print(df) #df.to_csv('file.txt',sep='|',index=False)
    

        name          tags
    0  alice             a
    1  bruce     [a, b, c]
    

    【讨论】:

    • 像魅力一样工作......谢谢!你能解释一下你的逻辑吗?
    • @igorkf df['tags'].str.len() 按行给出列表的长度,然后使用 .eq(1) 我们比较长度是否等于 1(返回布尔值 True 或 False),然后使用 np.where() 我们提取第一个条件为真的列表的字母,假的则保持不变。更多详情请查看np.where() docs
    猜你喜欢
    • 2015-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-15
    相关资源
    最近更新 更多