如何将另一列添加到我的数据帧,即我的另一列“标记”计数

2024-04-25 18:05:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我对python非常陌生,我正在尝试计算字符串中的标记数

我发现有人说要数逗号然后加1,这很有道理。没有意义的是,如何将它变成一列,应用于每一行。
我的数据帧称为data,设置如下:

product_id  sku       total_sold  tags           total_images 
grgeggre    rgerg     456         Up1_, Up2      5

我希望它看起来像下面这样:

product_id  sku       total_sold  tags           total_images  total tags
grgeggre    rgerg     456         Up1_, Up2      5             2

我试过:

tgs = data['tags']
tgsc = tgs.count("," in data["tags"] + str(1))
print(tgsc)

这不管用,有什么想法吗


Tags: iddatatagsproducttotalimagestgssku
1条回答
网友
1楼 · 发布于 2024-04-25 18:05:13

我认为apply的一个简单lambda函数应该可以做到:

data["total_tags"] = data["tags"].apply(lambda x : len(x.split(',')))

说明: DataFrame.apply():

Apply a function along an axis of the DataFrame.
Objects passed to the function are Series objects whose index is either the DataFrame’s index (axis=0) or the DataFrame’s columns (axis=1). By default (result_type=None), the final return type is inferred from the return type of the applied function. Otherwise, it depends on the result_type argument.

pandas documentation

因此,我们对列"tags"的数据帧的每一行应用一个函数(lambda函数)。
在本例中,lambda函数是一个匿名函数,x作为“输入参数”,而len(x.split(','))作为函数体。所以这个函数应用于"tags"列的每一行。
对于split()请参见str.split documentation,它将定义分隔符处的字符串拆分为一个数组。此数组的长度是逗号分隔的标记数

希望这个解释有用

相关问题 更多 >