Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/apache-flex/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 根据另一列的值对数据帧的一列应用函数,然后按groupby_Python 3.x_Pandas_Dataframe_Lambda - Fatal编程技术网

Python 3.x 根据另一列的值对数据帧的一列应用函数,然后按groupby

Python 3.x 根据另一列的值对数据帧的一列应用函数,然后按groupby,python-3.x,pandas,dataframe,lambda,Python 3.x,Pandas,Dataframe,Lambda,假设数据帧具有列“A”和列“condition”,如下代码所示 example = pd.DataFrame({'A': range(10), 'condition': [0,1,0,1,2,0,1,2,2,1]}) 如果“B”列中的值为0或2,我想将“A”列中的值乘以2。所以我试了这些: example['A']=example['A'].apply(lambda x: x*2 \ if example['condition']==0 or example['con

假设数据帧具有列“A”和列“condition”,如下代码所示

example = pd.DataFrame({'A': range(10), 'condition': [0,1,0,1,2,0,1,2,2,1]})
如果“B”列中的值为0或2,我想将“A”列中的值乘以2。所以我试了这些:

example['A']=example['A'].apply(lambda x: x*2 \
             if example['condition']==0 or example['condition']==2)

example['A']=np.where(example.condition==0 or example.condition==2, \
             lambda x: x*2, example.A)
但所有这些都无法获得如下所示的预期输出:

    output:                 desired output:
    example                 example
       A  B                          A  B
    0  0  0                      0   0  0
    1  1  1                      1   1  1
    2  2  0                      2   4  0
    3  3  1                      3   3  1
    4  4  2                      4   8  2
    5  5  0                      5  10  0
    6  6  1                      6   6  1
    7  7  2                      7  14  2 
    8  8  2                      8  16  2 
    9  9  1                      9   9  1  
如果我得到所需的输出,我想按“条件”分组,如果“A”值大于2.5,则计算“A”值的绝对总和。我有这个想法,但是如果我没有从上面得到想要的输出,我不确定它是否有效

group1=example.groupby([example[condition')['A'].\
       agg([ ('A sum' , lambda x : x[x>=2.5].abs(sum()) ])
有什么建议吗?

试试这个

df.loc[df['condition']%2==0, 'A'] = df['A']*2
O/p:


你最初的尝试非常接近。特别是,我将把条件带到它自己的单独函数中,以增强可读性,然后将该函数应用到具有
axis=1
的数据帧:

def f(row):
    if row["condition"] == 0 or row["condition"] == 2:
        return(int(row["A"] * 2))
    return(row["A"])   # Base condition 

example['B'] = example.apply(f, axis=1)   # Apply to rows of 'example' df

example.drop("condition", axis=1, inplace=True)

example

    A   condition   B
0   0   0   0
1   1   1   1
2   2   0   4
3   3   1   3
4   4   2   8
5   5   0   10
6   6   1   6
7   7   2   14
8   8   2   16
9   9   1   9
然后,要应用
groupby
操作:

example[example["A"] > 2.5].groupby("condition")["A"].apply(lambda x: np.sum(np.abs(x)))

condition
0     5
1    18
2    19
Name: A, dtype: int64

首先,我们得到
条件为0或2的所有行。然后我们用
A
值乘以其中两行,然后使用
GroupBy.sum
,同时使用
query
过滤
A>=2.5的所有行

m = example['condition'].isin([0,2])
example['A'] = np.where(m, example['A'].mul(2), example['A'])
grpd = example.query('A.ge(2.5)').groupby('condition', as_index=False)['A'].sum()
输出

   condition   A
0          0  28
1          1  18
2          2  76

详细信息
GroupBy.sum

首先,我们使用
query
获取
A>=2.5
的所有行:

example.query('A.ge(2.5)')

    A  condition
2   4          0
3   3          1
4   8          2
5  10          0
6   6          1
7  14          2
8  16          2
9   9          1
然后,我们使用groupby on condition获得每组唯一值,在本例中,所有具有
0
1
2
的行:

for _, d in grpd.groupby('condition', as_index=False):
    print(d, '\n')

    A  condition
2   8          0
5  20          0 

   A  condition
3  3          1
6  6          1
9  9          1 

    A  condition
4  16          2
7  28          2
8  32          2 
因此,如果我们有单独的组,我们可以使用
.sum
方法对整个
A
列求和:

for _, d in grpd.groupby('condition', as_index=False):
    print(d['A'].sum(), '\n')

28 

18 

76 

如果列“B”中的值为0或2,则可以使用np.where将列“A”中的值乘以2

example['A'] = np.where(example['condition'].isin([0,2]), example['A']*2,example['A'])
若要对满足条件的列执行求和,可以首先在数据帧示例中包含一个新列,说明A是>还是<2.5,然后在此数据帧上执行聚合

example['check_A'] =np.where(example['A']>2.5,1,0)
new = example.groupby(['condition','check_A'])['A'].apply(lambda c: c.abs().sum())

太好了,效果很好。只是一个问题。。。这里的绝对和是怎么工作的?还有一个小小的转折。。。在我的原始数据帧中,A列中的值是时间(HH:MM:SS),我希望小时数(HH)等于0或2。您建议如何编写此条件?@newielp我添加了更多解释和细节。请参阅编辑。这将显著更改您的问题,我认为此问题已得到回答。请随意发布一个新问题,这次请正确描述您的问题@非常感谢。。。顺便说一句,我需要更仔细地了解这个查询方法,等等。有趣的和需要研究的东西。我应用了这个:
grpd=example.groupby(['condition'])['A'].agg([('A sum',lambda x:x[x>=2.5].abs().sum())])
。但是这个查询在将来肯定会有用。谢谢,我可以根据你的建议调整我必须做的其他计算。谢谢,只是一个简单的问题:你将如何应用绝对总和?我需要求和,然后计算和值的abs()。
example['check_A'] =np.where(example['A']>2.5,1,0)
new = example.groupby(['condition','check_A'])['A'].apply(lambda c: c.abs().sum())