在Pandas_Python中合并求和和排除

时间:2018-06-22 15:34:33

标签: python pandas merge

我正在尝试使用此Python脚本合并重复的行。我将一列用逗号分隔,然后将其余部分求和,最后使用熊猫删除重复项,但是我需要从求和中排除一些行。例如,我不想将poly_area和total_area求和。我该怎么办?

import pandas as pd

output = r'C:dummy'

    fieldlist = ["FID","total_area","POLY_AREA", "PERCENTAGE","C5_3","M1_4","M1_4_R6A","M1_4_R6B", "M1_4_R7A", "M1_5_R10",
                 "M1_5_R7_3","M1_5_R9","M1_6_R10","PARK","R6A", "R6B", "R7A"]

    #Create dataframe from cursor
    df = pd.DataFrame.from_records(data=arcpy.da.SearchCursor('calculations', fieldlist), columns = fieldlist)

    #Create a new dataframe of FIDS and comma-separated percentages
    df1 = df.groupby("FID")["PERCENTAGE"].apply(lambda x: ", ".join(x.astype(str))).reset_index()

    #Create a new dataframe of sums per FID
    df2 = df.groupby("FID").sum()
    df2.drop("PERCENTAGE", axis=1, inplace=True)

    #Merge/join them together and export as csv
    df1.merge(df2, left_on="FID", right_index=True).to_csv(path_or_buf=output, index=False)

2 个答案:

答案 0 :(得分:1)

这将完成您的工作,只需替换您拥有的东西即可。

 #Create a new dataframe of FIDS and comma-separated percentages
df1 = df.groupby(["FID","total_area","POLY_AREA"])["PERCENTAGE"].apply(lambda x: ", ".join(x.astype(str))).reset_index()

#Create a new dataframe of sums per FID
df2 = df.groupby("FID").sum()
df2.drop(["total_area","POLY_AREA","PERCENTAGE"], axis=1, inplace=True)

答案 1 :(得分:0)

在创建df2时,您可以尝试获取列的子集,以便排除不需要的内容。具体尝试创建像这样的df2:

df2_cols = [col for col in fieldlist if col not in ['FID', 'total_area', 'POLY_AREA']]
df2 = df.groupby("FID")[df2_cols].sum()

创建合并的df后,您也可以只drop个不需要的列。