如何将2行合并为1行熊猫

时间:2020-02-15 08:12:08

标签: python-3.x pandas dataframe

我目前有一个数据框,它的第一个索引如下:

enter image description here

但是,当我向下滚动查看其他索引时,我意识到一些 tax_type 数据被拆分为 个人所得税 em> 和 企业所得税

enter image description here

我想做的是将分开的行合并为个人所得税和公司所得税,并将其重命名为 个人和公司所得税 ,然后在在此过程中,对它们携带的 no_of_cases tax_and_penalty_arising 进行汇总。

有人可以建议我如何做吗?

这是我目前尚未完成的源代码(实际上我不知道如何开始):

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

# import the csv file
dataname = 'Datasets\\tax-and-penalty-arising-from-audits-by-tax-type.csv'
data = pd.read_csv(dataname)
df = pd.DataFrame(data)

1 个答案:

答案 0 :(得分:2)

按字典使用Series.replace,然后汇总sum

d = {'Corporate Income Tax':'Individual and Corporate Income Tax',
     'Individual Income Tax':'Individual and Corporate Income Tax'}
df = df.groupby(['financial_year',df['tax_type'].replace(d)]).sum().reset_index()