数据帧列中的计数列表长度

2024-05-14 21:42:59 发布

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

这是我的数据帧:

CustomerID  InvoiceNo
0   12346.0 [541431, C541433]
1   12347.0 [537626, 542237, 549222, 556201, 562032, 57351]
2   12348.0 [539318, 541998, 548955, 568172]
3   12349.0 [577609]
4   12350.0 [543037]

期望输出:

 CustomerID InvoiceCount
0 12346.0   2
1 12347.0   6
2 12348.0   4
3 12349.0   1
4 12350.0   1

我想计算客户(CustomerID)拥有的发票总数。 请帮忙


Tags: 数据客户发票总数customeridinvoicenoinvoicecountc541433
3条回答

看看这是否有效:

df["InvoiceCount"] = df['InvoiceNo'].str.len()

如果你有真正的list,那么你可以这样做

df['InvoiceCount'] = df['InvoiceNo'].apply(len)

如果您有string和列表,那么您必须在计数之前将字符串转换为实际列表

df['InvoiceNo'] = df['InvoiceNo'].apply(eval)

但如果数字C541433(带C)正确并且可能需要

df['InvoiceCount'] = df['InvoiceNo'].apply(lambda x: len(x.split(',')))

或者类似于@datanearoor comment中的示例

df['InvoiceCount'] = df['InvoiceNo'].str.split(',').str.len()

最小工作示例

import pandas as pd
import io

text = '''CustomerID;InvoiceNo
12346.0;[541431, 541433]
12347.0;[537626, 542237, 549222, 556201, 562032, 57351]
12348.0;[539318, 541998, 548955, 568172]
12349.0;[577609]
12350.0;[543037]'''

df = pd.read_csv(io.StringIO(text), sep=';')

print( df['InvoiceNo'].apply(lambda x: len(eval(x))) )

print( df['InvoiceNo'].apply(eval).apply(len) )

print( df['InvoiceNo'].apply(lambda x: len(x.split(','))) )

print( df['InvoiceNo'].str.split(',').str.len() )

df['InvoiceNo'] = df['InvoiceNo'].apply(eval)
print( df['InvoiceNo'].apply(len) )

如果在列表中,可以使用函数“len”

假设列表在变量值中:

values = [537626, 542237, 549222, 556201, 562032, 57351]

那么金额是:

len(values) # 6

在本例中,这将返回6

相关问题 更多 >

    热门问题