相关疑难解决方法(0)

使用Groupby的Python Pandas条件求和

使用样本数据:

df = pd.DataFrame({'key1' : ['a','a','b','b','a'],
               'key2' : ['one', 'two', 'one', 'two', 'one'],
               'data1' : np.random.randn(5),
               'data2' : np. random.randn(5)})
Run Code Online (Sandbox Code Playgroud)

DF

    data1        data2     key1  key2
0    0.361601    0.375297    a   one
1    0.069889    0.809772    a   two
2    1.468194    0.272929    b   one
3   -1.138458    0.865060    b   two
4   -0.268210    1.250340    a   one
Run Code Online (Sandbox Code Playgroud)

我试图找出如何按key1对数据进行分组,并仅将key2等于'one'的data1值相加.

这是我尝试过的

def f(d,a,b):
    d.ix[d[a] == b, 'data1'].sum()

df.groupby(['key1']).apply(f, a = 'key2', b = 'one').reset_index()
Run Code Online (Sandbox Code Playgroud)

但这给了我一个"无"值的数据框

index   key1    0
0       a       None
1       b       None
Run Code Online (Sandbox Code Playgroud)

这里有什么想法?我正在寻找与以下SQL相当的Pandas:

SELECT Key1, SUM(CASE WHEN …
Run Code Online (Sandbox Code Playgroud)

python pandas pandas-groupby

21
推荐指数
2
解决办法
3万
查看次数

Pythonic计算pandas数据帧条纹的方法

给定df

df = pd.DataFrame([[1, 5, 2, 8, 2], [2, 4, 4, 20, 2], [3, 3, 1, 20, 2], [4, 2, 2, 1, 3], [5, 1, 4, -5, -4], [1, 5, 2, 2, -20], 
              [2, 4, 4, 3, -8], [3, 3, 1, -1, -1], [4, 2, 2, 0, 12], [5, 1, 4, 20, -2]],
             columns=['A', 'B', 'C', 'D', 'E'], index=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
Run Code Online (Sandbox Code Playgroud)

根据这个答案,我创建了一个计算条纹(向上,向下)的函数.

def streaks(df, column):
    #Create sign column
    df['sign'] = 0 …
Run Code Online (Sandbox Code Playgroud)

python numpy dataframe python-3.x pandas

6
推荐指数
1
解决办法
1018
查看次数

标签 统计

pandas ×2

python ×2

dataframe ×1

numpy ×1

pandas-groupby ×1

python-3.x ×1