gpt4 book ai didi

python - 如何用 Pandas 计算数据框中每个列表中的元素?

转载 作者:行者123 更新时间:2023-11-28 17:29:20 25 4
gpt4 key购买 nike

给定这样一个数据框df:

0     1
1 [12]
1 [13]
2 [11,12]
1 [10,0,1]
....

我想在每个df列表中计算某个值,例如'12'。所以我尝试了:

df.apply(list.count('12'))

但出现错误:TypeError: descriptor 'count' requires a 'list' object but received a 'str'。但它们正是 df[1] 中的列表!我该如何纠正它?谢谢!

最佳答案

我认为您可以先尝试通过 ix 选择列作为系列然后 apply函数 x.count(12):

import pandas as pd

d = { 0:pd.Series([1,1,2,1]),
1:pd.Series([[12], [13], [11,12 ],[10,0,1]])}

df = pd.DataFrame(d)

print df
0 1
0 1 [12]
1 1 [13]
2 2 [11, 12]
3 1 [10, 0, 1]

print df.ix[:, 1]
0 [12]
1 [13]
2 [11, 12]
3 [10, 0, 1]
Name: 1, dtype: object

print df.ix[:, 1].apply(lambda x: x.count(12))
0 1
1 0
2 1
3 0
Name: 1, dtype: int64

或者使用iloc选择:

print df.iloc[:, 1].apply(lambda x: x.count(12))   
0 1
1 0
2 1
3 0
Name: 1, dtype: int64

编辑:

我认为 1 列包含 NaN

您可以使用:

print df 
0 1
0 1 NaN
1 1 [13]
2 2 [11, 12]
3 1 [10, 0, 1]

print df.ix[:, 1].notnull()
0 False
1 True
2 True
3 True
Name: 1, dtype: bool

print df.ix[df.ix[:, 1].notnull(), 1].apply(lambda x: x.count(12))
1 0
2 1
3 0
Name: 1, dtype: int64

编辑2:

如果您想按索引(例如 0:2)和 1 列中的 NaN 进行过滤:

print df 
0 1
0 1 NaN
1 1 [13]
2 2 [11, 12]
3 1 [10, 0, 1]

#filter df by index - only 0 to 2
print df.ix[0:2, 1]
0 NaN
1 [13]
2 [11, 12]
Name: 1, dtype: object

#boolean series, where is not nul filtered df
print df.ix[0:2, 1].notnull()
0 False
1 True
2 True
Name: 1, dtype: bool

#get column 1: first is filtered to 0:2 index and then if is not null
print df.ix[0:2, 1][df.ix[0:2, 1].notnull()]
1 [13]
2 [11, 12]
Name: 1, dtype: object
#same as above, but more nice
df1 = df.ix[0:2, 1]
print df1
0 NaN
1 [13]
2 [11, 12]
Name: 1, dtype: object

print df1[df1.notnull()]
1 [13]
2 [11, 12]
Name: 1, dtype: object

#apply count
print df1[df1.notnull()].apply(lambda x: x.count(12))
1 0
2 1
Name: 1, dtype: int64

关于python - 如何用 Pandas 计算数据框中每个列表中的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35667713/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com