You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用pandas.sum()计算行和时,如何仅保留数值去除索引与dtype信息?

解决Pandas累计时间计算中Time列带索引和dtype的问题

直接修复你的循环代码

你的问题出在time = df.iloc[MyRow, 1:(trial+1)].sum(axis=1)返回的是Series对象,不是单个数值,存入DataFrame时会保留Series的索引和类型信息。只需要把Series提取成标量即可,比如用.iloc[0]或.values[0]:

import pandas as pd
df = pd.DataFrame([[1, 1, 1, 1], [2, 1, 2, 2], [3, 1, 3, 3], [4, 1, 4, 4], [5, 1, 5, 5]], columns = ['Subject', 'trial1', 'trial2', 'trial3'])
subjects = [1, 2, 3, 4, 5]

MyColumns = ['time', 'subject', 'trial']
sum_of_times = pd.DataFrame(columns=MyColumns)
for subject in subjects:
    for trial in range(1, 3):
        MyRow = df.loc[df['Subject'] == subject].index
        # 提取Series的唯一元素作为标量
        time = df.iloc[MyRow, 1:(trial+1)].sum(axis=1).iloc[0]
        new_row = [time, subject, trial]
        sum_of_times.loc[len(sum_of_times)] = new_row
        sum_of_times = sum_of_times.reset_index(drop=True)

print(sum_of_times)

运行后time列会只保留纯数值,完全匹配你的预期输出。


更高效的Pandas原生方法(适合60列场景)

手动嵌套循环效率较低,尤其面对60列的大规模数据时,用cumsum(逐行累计求和)+melt(宽表转长表)可以一步完成需求:

import pandas as pd
df = pd.DataFrame([[1, 1, 1, 1], [2, 1, 2, 2], [3, 1, 3, 3], [4, 1, 4, 4], [5, 1, 5, 5]], columns = ['Subject', 'trial1', 'trial2', 'trial3'])

# 1. 对所有trial列计算逐行累计时间
cumulative_df = df.set_index('Subject').cumsum(axis=1).reset_index()

# 2. 将宽表转换为长表,拆分trial编号和累计时间
sum_of_times = cumulative_df.melt(
    id_vars='Subject',
    var_name='trial',
    value_name='time'
)

# 3. 提取trial的数字编号,过滤到需要的范围(示例为1-2)并排序
sum_of_times['trial'] = sum_of_times['trial'].str.extract('(\d+)').astype(int)
sum_of_times = sum_of_times[sum_of_times['trial'].between(1, 2)]
sum_of_times = sum_of_times.sort_values(['Subject', 'trial']).reset_index(drop=True)

# 调整列名和顺序匹配预期输出
sum_of_times = sum_of_times[['time', 'Subject', 'trial']].rename(columns={'Subject': 'subject'})

print(sum_of_times)

这段代码输出结果和你预期完全一致,且无需手动遍历每个受试者和trial,处理大规模数据时效率更高。


内容的提问来源于stack exchange,提问作者Cam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 21:05:59