【发布时间】:2015-09-19 01:13:52
【问题描述】:
我正在尝试对文件执行一些简单的数学运算。
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 次,所以ids:1234 在current time (00:30:00) 的值是500,它要除以ids 出现的次数,然后添加到来自@987654338 的相应值@ 并使用当前时间创建一个新列。
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,然后将add 划分为对应的ref1 值,方法是使用@ 创建一个新列987654350@.
程序: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)
程序执行时没有错误也没有输出。需要一些修复建议。
【问题讨论】:
-
我想说你应该考虑重组你的数据。不要为每个“预处理”步骤添加新列,而是为您的数据提供固定数量的列,其中之一包括您当前用作新列标题的时间信息。也就是说,一个
current_time列,以及该列中具有“00:30:00”的一堆行,然后该列中具有“00:45:00”的一堆行,等等。 -
@BrenBarn 我无法进行重建,因为我也需要旧的时间序列计数以用于未来的绘图目的。
-
不确定你的意思。我所描述的更改不会导致任何信息丢失,只是格式不同。
-
@BrenBarn 能否以程序和输出格式显示,以便消除混乱?
-
我在答案中添加了更新,请查看。另外,你能检查一下中国行的预期输出吗?我想我得到了除那一行之外的所有行的预期结果。
标签: python csv datetime pandas multiple-columns