【发布时间】:2021-10-31 16:55:33
【问题描述】:
-
我想合并所有分数列小于 63 的行,
-
然后取出所有的一些并将它们保存在一个新行中,我们可以称之为“新总和”,它将是所有分数小于或等于 63 的分数的总和。
-
删除包含小于 63 的值的列。
-
我正在使用熊猫。
-
请看附图
【问题讨论】:
我想合并所有分数列小于 63 的行,
然后取出所有的一些并将它们保存在一个新行中,我们可以称之为“新总和”,它将是所有分数小于或等于 63 的分数的总和。
删除包含小于 63 的值的列。
我正在使用熊猫。
请看附图
【问题讨论】:
您可以这样做:
df.loc[len(df)] = ['Other', "", df[df['Score'] < 63]['Score'].sum(), ""]
如果你想删除Score
df.drop(df[df['Score'] < 63].index, inplace=True)
注意:选项inplace=True 永久更改DataFrame。如果您不希望将更改永久应用于DataFrame,请省略此选项,例如
new_df = df.drop(df[df['Score'] < 63].index)
演示:
import pandas as pd
import numpy as np
df = pd.DataFrame({
'Name': ['Alisa', 'Bobby', 'Cathrine', 'Alisa', 'Bobby', 'Cathrine', 'Alisa', 'Bobby', 'Cathrine', 'Alisa', 'Bobby',
'Cathrine'],
'Subject': ['Mathematics', 'Mathematics', 'Mathematics', 'Science', 'Science', 'Science', 'History', 'History',
'History', 'Economics', 'Economics', 'Economics'],
'Score': [62, 47, 55, 74, 31, 77, 85, 63, 42, 62, 89, 85],
'score-ranked': [7.5, 10.0, 9.0, 5.0, 12.0, 4.0, 2.5, 6.0, 11.0, 7.5, 1.0, 2.5]
})
df.loc[len(df)] = ['Other', "", df[df['Score'] < 63]['Score'].sum(), ""]
df.drop(df[df['Score'] < 63].index, inplace=True)
print(df)
输出:
Name Subject Score score-ranked
3 Alisa Science 74 5.0
5 Cathrine Science 77 4.0
6 Alisa History 85 2.5
7 Bobby History 63 6.0
10 Bobby Economics 89 1.0
11 Cathrine Economics 85 2.5
12 Other 299
【讨论】:
试试 df[df['分数'] > 63] df.groupby(['Name'])[Score].sum() 我写它作为答案,因为我不能评论
【讨论】:
你可以使用pandas内置的Fancy indexing:
df = df[df['score'] < 30]
df.loc[len(df.index)] = ["TOTAL","",sum(df['score']),""]
【讨论】: