pandas df里面有列表,AttributeError:“list”对象没有属性“split”[重复]

hs1ihplo  于 2023-04-18  发布在  其他
关注(0)|答案(2)|浏览(106)

此问题已在此处有答案

How to determine the length of lists in a pandas dataframe column(3个答案)
2天前关闭。
最初有此文本df(称为train

index                     train
0        My favourite food is anything I didn't have to...
1        Now if he does off himself, everyone will thin...
2                           WHY THE FUCK IS BAYLESS ISOING
3                              To make her feel threatened
4                                   Dirty Southern Wankers

我用这个来计算火车组中的单词:

def word_count(df):
word_count = []
for i in df['text']:
    word = i.split()
    word_count.append(len(word))
return word_count

train['word_count'] = word_count(train)

但是我忘了应用预处理了,在文本中应用预处理后,df是这样的

index                             train
0                     [favourit, food, anyth, didnt, cook]
1        [everyon, think, he, laugh, screw, peopl, inst...]
2                                     [fuck, bayless, iso]
3                                   [make, feel, threaten]
4                                [dirti, southern, wanker]

当我尝试使用def word_count(df):时,出现了一个错误:
AttributeError: 'list' object has no attribute 'split'
因为现在我有一个df,里面有列表。我怎么解决这个问题?

83qze16e

83qze16e1#

你不需要服装功能,而是这样做:

df['word_count'] = df['train'].apply(lambda x: len(x))
print(df)
train  word_count
0             [favourit, food, anyth, didnt, cook]           5
1  [everyon, think, he, laugh, screw, peopl, inst]           7
2                             [fuck, bayless, iso]           3
3                           [make, feel, threaten]           3
4                        [dirti, southern, wanker]           3
8ljdwjyq

8ljdwjyq2#

如果你已经有了list,使用str.len()

df['word_count'] = df['train'].str.len()
print(df)

# Output
                                             train  word_count
0             [favourit, food, anyth, didnt, cook]           5
1  [everyon, think, he, laugh, screw, peopl, inst]           7
2                             [fuck, bayless, iso]           3
3                           [make, feel, threaten]           3
4                        [dirti, southern, wanker]           3

相关问题