私は、長い間仕事で使用してきた集計関数を使用しています。関数に渡されるシリーズの長さが 1 の場合 (つまり、グループには 1 つの観測値のみがある場合)、その観測値が返されます。渡されるシリーズの長さが 1 より大きい場合、観測値はリストで返されます。
これは奇妙に思える人もいるかもしれませんが、これは X、Y の問題ではなく、この質問とは関係のない、これをやりたい正当な理由があります。
私が使用している関数は次のとおりです:
def MakeList(x):
""" This function is used to aggregate data that needs to be kept distinc within multi day
observations for later use and transformation. It makes a list of the data and if the list is of length 1
then there is only one line/day observation in that group so the single element of the list is returned.
If the list is longer than one then there are multiple line/day observations and the list itself is
returned."""
L = x.tolist()
if len(L) > 1:
return L
else:
return L[0]
何らかの理由で、現在作業中のデータ セットでは、関数が削減されないことを示す ValueError が発生します。以下は、私が使用しているテスト データと残りの手順です。
import pandas as pd
DF = pd.DataFrame({'date': ['2013-04-02',
'2013-04-02',
'2013-04-02',
'2013-04-02',
'2013-04-02',
'2013-04-02',
'2013-04-02',
'2013-04-02',
'2013-04-02',
'2013-04-02'],
'line_code': ['401101',
'401101',
'401102',
'401103',
'401104',
'401105',
'401105',
'401106',
'401106',
'401107'],
's.m.v.': [ 7.760,
25.564,
25.564,
9.550,
4.870,
7.760,
25.564,
5.282,
25.564,
5.282]})
DFGrouped = DF.groupby(['date', 'line_code'], as_index = False)
DF_Agg = DFGrouped.agg({'s.m.v.' : MakeList})
これをデバッグしようとして、次のような print ステートメントを入力したところprint L
、print x.index
出力は次のようになりました。
[7.7599999999999998, 25.564]
Int64Index([0, 1], dtype='int64')
[7.7599999999999998, 25.564]
Int64Index([0, 1], dtype='int64')
何らかの理由で、関数にシリーズが 2 回渡されているようですagg
。私の知る限り、これはまったく正常ではなく、おそらく関数が削減されない理由です。
たとえば、次のような関数を記述します。
def test_func(x):
print x.index
return x.iloc[0]
これは問題なく実行され、印刷ステートメントは次のようになります。
DF_Agg = DFGrouped.agg({'s.m.v.' : test_func})
Int64Index([0, 1], dtype='int64')
Int64Index([2], dtype='int64')
Int64Index([3], dtype='int64')
Int64Index([4], dtype='int64')
Int64Index([5, 6], dtype='int64')
Int64Index([7, 8], dtype='int64')
Int64Index([9], dtype='int64')
これは、各グループが関数にシリーズとして 1 回だけ渡されることを示します。
なぜこれが失敗するのか理解するのを手伝ってくれる人はいませんか? 私はこれまで、多くのデータ セットでこの関数を正常に使用してきました。
ありがとう
ベストアンサー1
理由はうまく説明できませんが、私の経験からするlist
と、pandas.DataFrame
それほどうまく機能しません。
私は通常tuple
代わりに以下を使用します。これでうまくいきます:
def MakeList(x):
T = tuple(x)
if len(T) > 1:
return T
else:
return T[0]
DF_Agg = DFGrouped.agg({'s.m.v.' : MakeList})
date line_code s.m.v.
0 2013-04-02 401101 (7.76, 25.564)
1 2013-04-02 401102 25.564
2 2013-04-02 401103 9.55
3 2013-04-02 401104 4.87
4 2013-04-02 401105 (7.76, 25.564)
5 2013-04-02 401106 (5.282, 25.564)
6 2013-04-02 401107 5.282