大Pandas列读取和添加列

2024-10-02 06:27:48 发布

您现在位置:Python中文网/ 问答频道 /正文

目前正在使用pandas和python加载大型CSV文件。我正在努力根据dataframe中三列中的多个值高效地创建和添加一个新列

共有三列(时间、二氧化碳和成本),我想根据一些计算结果添加一个名为gcost的新列

下面的代码可以工作,但速度非常慢。我认为正是这些项目拖了它的后腿:

输入

Id,time,CO2eq,cost

0,10,10,10

1,5,5,5

2,2,3,6

预期结果

Id,time,CO2eq,cost,gcost

0,10,10,10,X

1,5,5,5,X

2,2,3,6,X  


代码

#wftime, wfco2eq and wfcost are inputted from the front-end.
    hhinfo_input_df = pd.read_csv(input_file_path, header=0,
                              names=['Id','CO2eq', 'time', 'cost'])

    hhinfo_input_df['gcost'] = hhinfo_input_df.apply(cost_generate, axis=1)
    return hhinfo_input_df

#Normalized weighted values of each criterion (input by user)
def cost_generate(row):
    Norm_time = (row['time'] * (wftime / max_time)) * 100000
    Norm_co2eq = (row['CO2eq'] * (wfco2eq / max_co2eq)) * 100000
    Norm_cost = (row['cost'] * (wfcost / max_cost)) * 100000

    gcost = int(round(Norm_time)) + int(round(Norm_co2eq)) + int(round(Norm_cost))

    #gcost should never be 0.
    if gcost == 0:
        return 1
    return gcost

Tags: idnormdfinputreturntimemaxint
2条回答

不需要在行级别执行这些操作。如果您只使用这些操作的矢量化版本,Pandas将更快地处理这些操作:

df = pd.read_csv(input_file_path, header=0,
                 names=['Id','CO2eq', 'time', 'cost'])

Norm_time = (df['time'] * (wftime / max_time)) * 100000
Norm_co2eq = (df['CO2eq'] * (wfco2eq / max_co2eq)) * 100000
Norm_cost = (df['cost'] * (wfcost / max_cost)) * 100000
df["gcost"] = Norm_time.round().astype(int) + Norm_co2eq.round().astype(int) + Norm_cost.round().astype(int)

你能试着一次使用你所有的公式吗

例如:

import pandas as pd

data = [ ['A',2,1], ['B',1,3] ]

dataset = pd.DataFrame(data,columns= ['ID','Item1','Item2']

dataset['total'] = dataset['Item1'] + dataset['Item2']

相关问题 更多 >

    热门问题