Skip to main content
 首页 » 编程设计

python之列表 : How to set the dtype of items 的 Pandas 列

2025年05月04日14yyy_WW

我有一个数据框,它有多个包含列表的列,每行中列表的长度不同:

tweetid tweet_date    user_mentions       hashtags 
00112   11-02-2014    []                  [] 
00113   11-02-2014    [00113]             [obama, trump] 
00114   30-07-2015    [00114, 00115]      [hillary, trump, sanders] 
00115   30-07-2015    []                  [] 

数据框是三个不同数据框的连接,我不确定列表中的项目是否具有相同的数据类型。例如,在 user_mentions 列中,有时数据如下:

[00114, 00115] 

但有时候是这样的:

['00114','00115']  

如何为列表中的项目设置数据类型?

请您参考如下方法:

Pandas DataFrames 并非真正设计用于将列表作为行/列值,所以这就是您面临困难的原因。你可以做

python3.x:

df['user_mentions'].apply(lambda x: list(map(int, x))) 

python2.x:

df['user_mentions'].apply(lambda x: map(int, x)) 

在 python3 中,当返回一个映射对象时,您必须转换为列表,在 python2 中,这不会发生,因此您不会明确地将其称为列表。

在上面的 lambda 中,x 是您的行 list,您正在将值映射到 int。