pandas 熊猫中的列表理解

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40646458/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 02:27:03  来源:igfitidea点击:

list comprehension in pandas

pythonpandaslist-comprehension

提问by WhitneyChia

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.

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

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']]

I get an error of:

我收到以下错误:

ValueError: Length of values does not match length of index

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

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

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

回答by Kartik

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

本质上,您的列表理解语句是一组 3 个嵌套循环。在代码中:

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

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:

结果列表的长度将是 DataFrame 长度的 3 倍。因此错误。要修复,您需要等效于:

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

In terms of list comprehension:

在列表理解方面:

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

回答by jtitusj

The reason why your new method doesn't work is because the list comprehension produces data that is longer than the number of indices in your dataframe. A quick fix for that would be something like:

您的新方法不起作用的原因是列表理解生成的数据比数据框中的索引数长。对此的快速解决方法如下:

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

回答by Lorenz

If you do not want to repeat df2 for each column:

如果您不想为每一列重复 df2:

[row[0][0]*row[0][1]-row[0][2] for row in zip(df2[['apples', 'oranges', 'bananas']].to_numpy())]

or

或者

def func(row):
    print(row[0]*row[1]-row[2])

[func(*row) for row in zip(df2[['apples', 'oranges', 'bananas']].to_numpy())]

See also:

也可以看看: