在熊猫单元格中添加值

时间:2020-01-19 07:12:41

标签: python pandas sum

我正在尝试在Pandas Dataframe中一列的单元格中添加值。数据框已创建:

data = [['ID_123456', 'example=1(abc)'], ['ID_123457', 'example=1(def)'], ['ID_123458', 'example=1(try)'], ['ID_123459', 'example=1(try)'], ['ID_123460', 'example=1(try),2(test)'], ['ID_123461', 'example=1(try),2(test),9(yum)'], ['ID_123462', 'example=1(try)'], ['ID_123463', 'example=1(try),7(test)']]

df = pd.DataFrame(data, columns = ['ID', 'occ'])

display(df)

该表如下所示:

ID          occ
ID_123456   example=1(abc)
ID_123457   example=1(def)
ID_123458   example=1(try)
ID_123459   example=1(test)
ID_123460   example=1(try),2(test)
ID_123461   example=1(try),2(test),9(yum)
ID_123462   example=1(test)
ID_123463   example=1(try),7(test)

以下链接与此相关,但是我无法在数据框上运行命令。

Sum all integers in a PANDAS DataFrame "cell"

该命令给出“字符串索引超出范围”的错误。

输出应如下所示:

ID          occ                              count
ID_123456   example=1(abc)                     1
ID_123457   example=1(def)                     1
ID_123458   example=1(try)                     1
ID_123459   example=1(test)                    1
ID_123460   example=1(try),2(test)             3
ID_123461   example=1(try),2(test),9(yum)      12
ID_123462   example=1(test)                    1
ID_123463   example=1(try),7(test)             8

1 个答案:

答案 0 :(得分:2)

如果要对class_name列上的所有数字求和,请使用Series.str.extractall,并用base.name转换为整数:

def post(self, request,token):
    if request.method=="POST":
        form = RestorePasswordForm(request.POST)
        if form.is_valid():
        obj = token(token)
        if obj:
            this_user = User.objects.get(id=obj.email_id)
            if not this_user:
              return False
            this_user.set_password(request.POST.get('new_password2'))
            this_user.save()
            obj.token = None
            obj.save()
      else:
           print("you didn't post anything to form")
    return JsonResponse({"message":form.errors})