【问题标题】:Sum values in column 3 related to unique values in column 2 and 1第 3 列中的总和值与第 2 列和第 1 列中的唯一值相关
【发布时间】:2018-06-13 13:41:26
【问题描述】:

我正在使用 Python,我有一个来自纽约市的优步数据的 Pandas DataFrame。 DataFrame 的一部分如下所示:

    Year Week_Number    Total_Dispatched_Trips      
    2015    51          1,109
    2015    5           54,380
    2015    50          8,989
    2015    51          1,025
    2015    21          10,195
    2015    38          51,957
    2015    43          266,465
    2015    29          66,139
    2015    40          74,321
    2015    39          3
    2015    50          854

就像现在一样,同一周每年都会出现多次。我想对每年每周的“Total_Dispatched_Trips”值求和。我希望每个星期每年只出现一次。 (因此 2015 年等第 51 周不能多次出现)。我该怎么做呢?我的数据集超过 3k 行,所以我不希望手动执行此操作。

提前致谢。

【问题讨论】:

    标签: python pandas sorting sum grouping


    【解决方案1】:

    okidoki 就在这里,借Convert number strings with commas in pandas DataFrame to float

    import locale
    from locale import atof
    locale.setlocale(locale.LC_NUMERIC, '')
    
    df['numeric_trip'] = pd.to_numeric(df.Total_Dispatched_trips.apply(atof), errors = 'coerce')
    df.groupby(['Year', 'Week_number']).numeric_trip.sum()
    

    【讨论】:

    • Total_Dispatched_Trips ,根据他提供的数据,该列的dtype应该是str
    • pd.to_numeric('1,109',errors='coerce') 是否应该返回 1109?据我所知,它返回nan
    • @ℕʘʘḆḽḘ 运行代码后,“numeric_trip”的大部分值都是“NaN”。这是什么原因?
    • 现在请再试一次
    • @ℕʘʘḆḽḘ 运行更新后的代码时出现以下错误:AttributeError: 'Series' object has no attribute 'applymap'
    猜你喜欢
    • 2019-09-12
    • 2018-11-02
    • 1970-01-01
    • 2018-12-25
    • 1970-01-01
    • 1970-01-01
    • 2016-09-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多