【问题标题】:Creating a column from a string slice in Pandas从 Pandas 中的字符串切片创建列
【发布时间】:2020-12-27 12:40:56
【问题描述】:

有人知道为什么这会在“2_stars”列中显示 NaN 值吗?提前致谢

data['1_star']=data['Sentiment'].str.slice(31,40)
data['start'] = data['Sentiment'].str.find("'2 stars', 'score': ") + len("'2 stars', 'score': ")
data['end'] = data['Sentiment'].str.find("}, {'label': '3 stars'")
data['2_stars']=data['Sentiment'].str.slice(data['start'],data['end'])

【问题讨论】:

    标签: python pandas string slice


    【解决方案1】:

    Pandas str.slice 使用标量数字,而不是所有列值。所以需要DataFrame.apply中的每行处理:

    data['2_stars']= data.apply(lambda x: x['Sentiment'][slice(x['start'], x['end'])], axis=1)
    

    列表理解的另一个想法:

    zipped = zip(data['Sentiment'], data['start'], data['end'])
    data['2_stars'] = [a[slice(s, e)] for a, s, e in zipped]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-10-15
      • 2021-03-29
      • 2021-12-28
      • 2015-09-15
      • 2022-07-06
      • 2018-05-03
      相关资源
      最近更新 更多