python - Pandas 数据帧 : create a column from a list inside a column

标签 python list pandas col

我有 pandas DataFrame 'test_df':

email                      my_list
email1@email1.com          [1,9,3,5]
email2@email2.com          [6,3,3,15]
email3@email3.com          [7,7,2,5]
email4@email4.com          [5,5,5,5]

我怎样才能拥有以下 DataFrame(取“my_list”的前 2 个元素):

email                      col1             col2             
email1@email1.com          1                9        
email2@email2.com          6                3
email3@email3.com          7                7
email4@email4.com          5                5           

我尝试过:

test_df['col1'] = test_df['my_list'][0]
test_df['col2'] = test_df['my_list'][1]

但它不起作用

最佳答案

我问了一个相关问题here ,尽管我想超出将列表扩展为列的范围,因此答案比您需要的更复杂。对于您的情况,您可以这样做:

# Using my own example data since it's a bit tough to copy-paste
# a printed table and have the lists show up as lists
df = pd.DataFrame({'email': ['email1@eg.com', 'email2@eg.com'], 
                   'lists': [[1, 9, 3, 5], [6, 3, 3, 15]]})
df
Out[14]: 
           email          lists
0  email1@eg.com   [1, 9, 3, 5]
1  email2@eg.com  [6, 3, 3, 15]

objs = [df, pd.DataFrame(df['lists'].tolist()).iloc[:, :2]]
pd.concat(objs, axis=1).drop('lists', axis=1)
Out[13]: 
           email  0  1
0  email1@eg.com  1  9
1  email2@eg.com  6  3

关于python - Pandas 数据帧 : create a column from a list inside a column,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27895685/

相关文章:

python - 按索引seaborn散点图颜色/标记

python - 使用 selenium 读取多个文本元素时出现错误消息

python-3.x - pandas groupby apply 不会广播到 DataFrame

python - 使用正则表达式提取文件名

html - CSS:缩小导航菜单中元素符号之间的距离

python - 如何转发/填充 Pandas DataFrame 列/系列中的特定值?

C++通过迭代器访问指向对象成员的指针列表

c++ - 检查容器类型

python - OpenCV 教程 - 错误 : Unsupported format or combination of formats

python - Scikit Learn - 通过加载 CSV 识别目标