【发布时间】:2018-08-06 19:49:57
【问题描述】:
我不断收到以下错误。
我读取了一个包含 3 列时间序列数据的文件:[meter ID] [daycode(稍后解释)] [meter reading in kWh]
consum = pd.read_csv("data/File1.txt", delim_whitespace=True, encoding = "utf-8", names =['meter', 'daycode', 'val'], engine='python')
consum.set_index('meter', inplace=True)
test = consum.loc[[1048]]
我将观察此文件中所有数据长度的仪表读数,但首先按仪表 ID 过滤。
test['day'] = test['daycode'].astype(str).str[:3]
test['hm'] = test['daycode'].astype(str).str[-2:]
为了可读性,我根据其规则转换日码。前 3 位数字在 1 到 365 x2 = 730 范围内,后 2 位数字在 1 到 48 范围内。这些是 2 年长度的 30 分钟间隔读数。 (但不是全部都有)
所以我创建了一个文件,其中一个包含日期,另一个分别包含时间。我将使用 index 将 daycode 的数字转换为这些文件包含的相应日期和时间。
#dcodebook index starts from 0. So minus 1 from the daycode before match
dcodebook = pd.read_csv("data/dcode.txt", encoding = "utf-8", sep = '\r', names =['match'])
#hcodebook starts from 1
hcodebook = pd.read_csv("data/hcode.txt", encoding = "utf-8", sep ='\t', lineterminator='\r', names =['code', 'print'])
hcodebook = hcodebook.drop(['code'], axis= 1)
由于某种奇怪的原因,据我所知,dcodebook 是使用 .iloc 函数索引的,但 hcodebook 需要 .loc。
#iloc: by int-position
#loc: by label value
#ix: by both
day_df = dcodebook.iloc[test['day'].astype(int) - 1].reset_index(drop=True)
#to avoid duplicate index Valueerror, create separate dataframes..
hm_df = hcodebook.loc[test['hm'].astype(int) - 1]
#.to_frame error / do I need .reset_index(drop=True)?
下一行是代码崩溃的地方。
datcode_df = day_df(['match']) + ' ' + hm_df(['print'])
print datcode_df
print test
我不明白的:
- 我之前测试过,不同数据帧的列可以使用所示的简单加法进行合并
- 我最初将其分配给测试数据框中的现有列 ['daycode'],以便替换以前的值。并且返回了相同的错误消息。
请指教。
【问题讨论】:
-
您需要将
()中的datcode_df = day_df(['match']) + ' ' + hm_df(['print'])删除到datcode_df = day_df['match'] + ' ' + hm_df['print'] -
很难没有数据,但是
hm_df = hcodebook.loc[test['hm'].astype(int) - 1].reset_index(drop=True)呢? -
但也需要两个DataFrames的szie相同,所以
day和hm是唯一的。 -
是的,这似乎正是问题所在,你太棒了。
-
没有办法,因为 [day] [hm] 是从同一列中拆分出来的!但也要仔细检查!谢谢!
标签: pandas dataframe merge typeerror