pandas 列表理解 [英] list comprehension in pandas

查看:42
本文介绍了 pandas 列表理解的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在举一个玩具示例,但它将帮助我了解我正在尝试做的其他事情的情况.假设我想在数据框optimal_fruit"中添加一个新列,即苹果 * 橙子 - 香蕉.

I'm giving a toy example but it will help me understand what's going on for something else I'm trying to do. Let's say I want a new column in a dataframe 'optimal_fruit' that is apples * orange - bananas.

我可以做这样的事情来得到它.

I can do something like this to get it.

df2['optimal_fruit'] = df2['apples'] * df2['oranges'] - df2['bananas'] 


apples  oranges bananas optimal_fruit
1       6       11      -5
2       7       12      2
3       8       13      11
4       9       14      22
5       10      15      35

如果我尝试做这样的事情怎么办?而我该如何在列表理解中做到这一点?

What is happening if I try to do something like this? And how could I do this in a list comprehension?

df2['optimal_fruit'] = [x * y - z for x in df2['apples'] for y in df2['oranges'] for z in df2['bananas']]

我收到以下错误:

ValueError:值的长度与索引的长度不匹配

ValueError: Length of values does not match length of index

一如既往,非常感谢您的帮助!

As always, thank you all so much for your help!

推荐答案

基本上,您的列表理解语句是3个嵌套循环的集合.在代码中:

Essentially your list comprehension statement is a set of 3 nested loops. In code:

l = []
for x in df2['apples']:
    for y in df2['oranges']:
        for z in df2['bananas']:
            l.extend([x * y - z])

结果列表的长度将是DataFrame长度的3倍.因此,错误.要解决此问题,您需要执行以下操作:

The length of your resultant list will be 3 times the length of your DataFrame. Hence the error. To fix, you need the equivalent of:

for x, y, z in zip(df2['apples'], df2['oranges'], df2['bananas']):
    l.extend([x * y - z])

关于列表理解:

[x * y - z for x, y, z in zip(df2['apples'], df2['oranges'], df2['bananas'])]

这篇关于 pandas 列表理解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆