我有一个 dataframe
test = pd.DataFrame({'col1':[1,2,3], 'col2':['a','b','c']})
test
Out[79]:
col1 col2
0 1 a
1 2 b
2 3 c
我想计算以下的 “初差”。col1
明确使用 iloc
但结果却是胡说八道。
test.iloc[1:,0] - test.iloc[:-1,0]
Out[80]:
0 NaN
1 0.0
2 NaN
Name: col1, dtype: float64
我知道我可以用 pandas.DataFrame.diff
但我需要了解的机理的 iloc
导致失败。
解决方案:
问题是两个对象之间的索引值不同。
print (test.iloc[1:,0])
1 2
2 3
Name: col1, dtype: int64
print (test.iloc[:-1,0])
0 1
1 2
Name: col1, dtype: int64
可能的解决方案是创建相同的索引值:
a = test.iloc[1:,0].reset_index(drop=True) - test.iloc[:-1,0])
print (a)
0 1
1 1
Name: col1, dtype: int64
或者如果长度总是相同的话 将一个值转换为numpy数组:
a = test.iloc[1:,0] - test.iloc[:-1,0].values
print (a)
1 1
2 1
Name: col1, dtype: int64