我有一个非常大的 pandas DataFrame,其中 'account_type'
列下的单个值 'Standard'
有多行,但其他列标题中不同行的数值不同.
是否有一种方法可以组合 'Standard'
的所有数值,而无需组合每行的字符串?我有 180 列需要完成此操作。
示例:
df = pd.DataFrame([
['Standard', 0.2],
['Standard', 0.3],
['Standard', 0.2],
['Standard', 0.4],
['Standard', 0.6],
['Standard', 0.3]],
columns=['account_type', 'cost'])
只想要:
account_type cost
'Standard' 2.0
编码经验最少,如果不清楚,请道歉。
最佳答案
仅按boolean indexing
过滤标准
行对于新的 DataFrame
使用构造函数:
a = df.loc[df['account_type'] == 'Standard', 'cost'].sum()
print (a)
2.0
df = pd.DataFrame([['Standard', a]], columns=['account_type', 'cost'])
print (df)
account_type cost
0 Standard 2.0
如果所有值都是标准
:
df = pd.DataFrame([['Standard', df['cost'].sum()]], columns=['account_type', 'cost'])
如果希望所有可能的 acount_type
值都可以聚合 sum
:
df = pd.DataFrame([
['Standard1', 0.2],
['Standard1', 0.3],
['Standard1', 0.2],
['Standard2', 0.4],
['Standard2', 0.6],
['Standard', 0.3]], columns=['account_type', 'cost'])
print (df)
account_type cost
0 Standard1 0.2
1 Standard1 0.3
2 Standard1 0.2
3 Standard2 0.4
4 Standard2 0.6
5 Standard 0.3
df1 = df.groupby('account_type', as_index=False)['cost'].sum()
print (df1)
account_type cost
0 Standard 0.3
1 Standard1 0.7
2 Standard2 1.0
编辑:
如果需要所有数字列的总和
:
df = pd.DataFrame({
'account_type':['Standard'] * 5 + ['another val'],
'B':[4,5,4,5,5,4],
'C':[7,8,9,4,2,3],
'D':[1,3,5,7,1,0],
'E':[5,3,6,9,2,4],
'F':list('aaabbb')
})
print (df)
account_type B C D E F
0 Standard 4 7 1 5 a
1 Standard 5 8 3 3 a
2 Standard 4 9 5 6 a
3 Standard 5 4 7 9 b
4 Standard 5 2 1 2 b
5 another val 4 3 0 4 b
cols = df.select_dtypes(np.number).columns
s = df.loc[df['account_type'] == 'Standard', cols].sum()
print (s)
B 23
C 30
D 17
E 25
dtype: int64
df1 = s.to_frame().T
df1.insert(0, 'account_type', 'Standard')
print (df1)
account_type B C D E
0 Standard 23 30 17 25
关于python - 组合 Pandas DataFrame 中的数字列值以获取重复行而不组合字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53066360/