我有一個如下所示的資料集:
Value Type X_sq
-1.975767 Weather
-0.540979 Fruits
-2.359127 Fruits
-2.815604 Corona
-0.929755 Weather
我想遍歷每一行并計算上面每一行的平方和(僅當型別匹配時)。我想把這個值放在 X.sq 列中。
例如,在第一行,上面什么都沒有。所以只有(-1.975767 x -1.975767)。在第二行中,它上面沒有 FRUITS 行,所以它只是 -0.540979 x -0.540979。但是,在第三行中,當我們掃描所有之前的行時,我們應該會發現 FRUITS 已經存在。所以我們應該得到最后一個 FRUIT 的 ..... X_sq值并計算一個新的平方和。
Value Type X_sq
-1.975767 Weather -1.975767 * -1.975767 = x
-0.540979 Fruits -0.540979 * -0.540979 = y
-2.359127 Fruits y ( -2.359127 x -2.359127)
-2.815604 Corona -2.815604 * -2.815604
-0.929755 Weather x (-0.929755 * -0.929755)
我試過了,效果很好:
df['sumOfSquares'] = df['value'].pow(2).groupby(df['type']).cumsum()
但是,現在我想根據兩個列進行分組:這樣 Country 和 Type 都匹配。
Value Type X_sq Country
-1.975767 Weather Albania
-0.540979 Fruits Brazil --should be grouped
-2.359127 Fruits Brazil --should be grouped
-2.815604 Corona Albania
-0.929755 Weather Chine
我在這里試過這個(型別=主題):
df['sumOfSquares'] = df['value'].pow(2).groupby(['themes', 'suppliers_country']).cumsum()
但是,即使資料集中存在“型別”,它也會給我這個錯誤
----> 1 df['sumOfSquares'] = df['avg_country_tone'].pow(2).groupby(['themes', 'suppliers_country']).cumsum()
File /usr/local/Cellar/ipython/8.0.1/libexec/lib/python3.10/site-packages/pandas/core/series.py:1929, in Series.groupby(self, by, axis, level, as_index, sort, group_keys, squeeze, observed, dropna)
1925 axis = self._get_axis_number(axis)
1927 # error: Argument "squeeze" to "SeriesGroupBy" has incompatible type
1928 # "Union[bool, NoDefault]"; expected "bool"
-> 1929 return SeriesGroupBy(
1930 obj=self,
1931 keys=by,
1932 axis=axis,
1933 level=level,
1934 as_index=as_index,
1935 sort=sort,
1936 group_keys=group_keys,
1937 squeeze=squeeze, # type: ignore[arg-type]
1938 observed=observed,
1939 dropna=dropna,
1940 )
File /usr/local/Cellar/ipython/8.0.1/libexec/lib/python3.10/site-packages/pandas/core/groupby/groupby.py:882, in GroupBy.__init__(self, obj, keys, axis, level, grouper, exclusions, selection, as_index, sort, group_keys, squeeze, observed, mutated, dropna)
879 if grouper is None:
880 from pandas.core.groupby.grouper import get_grouper
--> 882 grouper, exclusions, obj = get_grouper(
883 obj,
884 keys,
885 axis=axis,
886 level=level,
887 sort=sort,
888 observed=observed,
889 mutated=self.mutated,
890 dropna=self.dropna,
891 )
893 self.obj = obj
894 self.axis = obj._get_axis_number(axis)
File /usr/local/Cellar/ipython/8.0.1/libexec/lib/python3.10/site-packages/pandas/core/groupby/grouper.py:882, in get_grouper(obj, key, axis, level, sort, observed, mutated, validate, dropna)
880 in_axis, level, gpr = False, gpr, None
881 else:
--> 882 raise KeyError(gpr)
883 elif isinstance(gpr, Grouper) and gpr.key is not None:
884 # Add key to exclusions
885 exclusions.add(gpr.key)
KeyError: 'themes'
even though themes is there. Themes = type
uj5u.com熱心網友回復:
發生錯誤是因為您正在對 pd 系列進行分組,并且它沒有名為'themes', 'suppliers_country'. 要對一個系列進行分組,您必須將groupby另一個系列而不是字串作為引數傳遞。嘗試將字串列連接到單個系列中,并分組為:
df['sumOfSquares'] = df['Value'].pow(2).groupby(df.Type "__" df.Country).cumsum()
或者,您也可以按 2 個不同的系列進行分組(我認為這是您的第一個想法):
df['sumOfSquares'] = df['Value'].pow(2).groupby([df.Type,df.Country]).cumsum()
uj5u.com熱心網友回復:
您可以在此處創建新的幫助列,new因此可以使用您的解決方案來定義列名稱groupby:
df['sumOfSquares'] = (df.assign(new = df['avg_country_tone'].pow(2))
.groupby(['themes', 'suppliers_country'])['new']
.cumsum())
uj5u.com熱心網友回復:
如果要合并Type和Country列以獲得總和,請使用:
out = df.assign(X_sq=df['Value'].pow(2)).groupby(['Type', 'Country'])['X_sq'] \
.sum().reset_index()
print(out)
# Output
Type Country X_sq
0 Corona Albania 7.927626
1 Fruits Brazil 5.858138
2 Weather Albania 3.903655
3 Weather Chine 0.864444
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/424173.html
上一篇:在python中合并資料類
