2017-08-11 4 views
1

私はパンダのDataFrameを持っています。私はすべての負の値をresult1として集計するのに役立つ関数を書いています。結果2。だから、基本的には、この機能は、私は、これはあまりにも混乱していないことを願うコラム「total_load」パンダデータフレームのある行の特定の値を集計する関数を書く

example of the dataframe

def total_battery(ok6, col_name='total_load'): 
"""Return a dictionary with counts of occurrences.""" 


# Initialize an empty dictionary: cols_values 
cols_values = {} 

# Extract column from df: col 
col = ok6[col_name] 

# iterate over the column in df 
for entry in col: 


    if entry in cols_values.keys() < 0: ***--> then sum all the negative values*** 
     cols_values[entry] += sum 

    else: 
     if entry in cols_values.keys() > 0: ***--> then sum all the negative values*** 
      cols_values[entry] += sum 


    # Return the cols_count dictionary 
    return cols_values 

# Call count_entries(): result1 
result1 = total_battery(ok6, "total_load") 

# Call count_entries(): result2 
result2 = total_battery(ok6, "total_load") 

# Print result1 and result2 
print(result1) 
print(result2) 

を反復処理する必要があります。

ありがとうございました。

答えて

1

フィルタリングの使用boolean indexingまたはquery、その後Series.sum

result1 = df.loc[df['total_load'] < 0, 'total_load'].sum() 
result2 = df.loc[df['total_load'] > 0, 'total_load'].sum() 

result1 = df.query('total_load < 0')['total_load'].sum() 
result2 = df.query('total_load > 0')['total_load'].sum() 

サンプル

rng = pd.date_range('2016-06-01', periods=4, freq='T') 
df = pd.DataFrame({'total_load':[1,2,-3,-5]}, index=rng) 
print (df) 
        total_load 
2016-06-01 00:00:00   1 
2016-06-01 00:01:00   2 
2016-06-01 00:02:00   -3 
2016-06-01 00:03:00   -5 

result1 = df.loc[df['total_load'] < 0, 'total_load'].sum() 
result2 = df.loc[df['total_load'] > 0, 'total_load'].sum() 
print (result1) 
-8 
print (result2) 
3 

result1 = df.query('total_load < 0')['total_load'].sum() 
result2 = df.query('total_load > 0')['total_load'].sum() 
print (result1) 
-8 
print (result2) 
3 
+0

素晴らしいことだと多くのより簡単^^あなたはjezraelありがとう! – harald12345

+0

はい。私は最初に純粋なpythonをデータ解析にも使用しますが、パフォーマンスを上げるために私はパンダを使い始めます。それは非常に良い決断だった:)幸運を! – jezrael

関連する問題