我正在尝试对文件执行一些简单的数学运算。
下面的file_1.csv文件中的列是动态的,列数会随着时间的推移而增加。因此,我们不能有固定的last_column。
master_ids.csv:在任何预处理之前。
在这里,
程序:由Jianxun Li编写。
程序没有出现错误,也没有输出任何内容。请提供一些修复建议。
下面的file_1.csv文件中的列是动态的,列数会随着时间的推移而增加。因此,我们不能有固定的last_column。
master_ids.csv:在任何预处理之前。
Ids,ref0 #the columns increase dynamically
1234,1000
8435,5243
2341,563
7352,345
master_count.csv
: 在任何处理之前
Ids,Name,lat,lon,ref1
1234,London,40.4,10.1,500
8435,Paris,50.5,20.2,400
2341,NewYork,60.6,30.3,700
7352,Japan,70.7,80.8,500
1234,Prague,40.4,10.1,100
8435,Berlin,50.5,20.2,200
2341,Austria,60.6,30.3,500
7352,China,70.7,80.8,300
master_Ids.csv
:经过一次预处理之后
Ids,ref,00:30:00
1234,1000,500
8435,5243,300
2341,563,400
7352,345,500
master_count.csv
:期望的输出结果(追加/合并)
Ids,Name,lat,lon,ref1,00:30:00
1234,London,40.4,10.1,500,750
8435,Paris,50.5,20.2,400,550
2341,NewYork,60.6,30.3,700,900
7352,Japan,70.7,80.8,500,750
1234,Prague,40.4,10.1,100,350
8435,Berlin,50.5,20.2,200,350
2341,Austria,60.6,30.3,500,700
7352,China,70.7,80.8,300,750
例如:Ids:1234
出现了 2
次,因此在 当前时间(00:30:00)
时,ids: 1234
的值为 500
,应该除以出现的 ids
次数,然后加上来自 ref1
的相应值,并创建一个具有当前时间的新列。
master_Ids.csv
:经过另一种预处理之后
Ids,ref,00:30:00,00:45:00
1234,1000,500,100
8435,5243,300,200
2341,563,400,400
7352,345,500,600
master_count.csv
:另一次执行(合并/追加)后的预期输出
Ids,Name,lat,lon,ref1,00:30:00,00:45:00
1234,London,40.4,10.1,500,750,550
8435,Paris,50.5,20.2,400,550,500
2341,NewYork,60.6,30.3,700,900,900
7352,Japan,70.7,80.8,500,750,800
1234,Prague,40.4,10.1,100,350,150
8435,Berlin,50.5,20.2,200,350,300
2341,Austria,60.6,30.3,500,700,700
7352,China,70.7,80.8,300,750,600
在这里,
current time
是00:45:00
,我们将current time value
除以ids
出现的count
,然后通过创建一个带有new current time
的新列,add
到相应的ref1
值中。程序:由Jianxun Li编写。
import pandas as pd
import numpy as np
csv_file1 = '/Data_repository/master_ids.csv'
csv_file2 = '/Data_repository/master_count.csv'
df1 = pd.read_csv(csv_file1).set_index('Ids')
# need to sort index in file 2
df2 = pd.read_csv(csv_file2).set_index('Ids').sort_index()
# df1 and df2 has a duplicated column 00:00:00, use df1 without 1st column
temp = df2.join(df1.iloc[:, 1:])
# do the division by number of occurence of each Ids
# and add column any time series
def my_func(group):
num_obs = len(group)
# process with column name after next timeseries (inclusive)
group.iloc[:,4:] = (group.iloc[:,4:]/num_obs).add(group.iloc[:,3], axis=0)
return group
result = temp.groupby(level='Ids').apply(my_func)
程序没有出现错误,也没有输出任何内容。请提供一些修复建议。