[英]shift a column in a pandas dataframe will set data to NaN
I try to shift a column in a dataframe, before I found shift method, I try to do it myself.我尝试在数据框中移动一列,在找到shift方法之前,我尝试自己做。 I found something intersting.
我发现了一些有趣的东西。
Here is the code这是代码
create the dataframe:创建数据框:
df = pd.DataFrame(np.random.randn(5,3))
Here is the data:这是数据:
0 1 2
0 -0.274583 0.141030 1.335455
1 -0.887131 -1.253900 0.395358
2 -0.194082 -0.462745 -0.237422
3 0.095535 0.236268 -1.347387
4 2.210129 -0.816895 -1.225560
if I do this to shift the last column up 2 rows:如果我这样做是为了将最后一列向上移动 2 行:
df.loc[0:2,2] = df.loc[2:,2]
The result is, the first 2 rows are NaN结果是,前两行是 NaN
0 1 2
0 -0.274583 0.141030 NaN
1 -0.887131 -1.253900 NaN
2 -0.194082 -0.462745 -0.237422
3 0.095535 0.236268 -1.347387
4 2.210129 -0.816895 -1.225560
What is the problem here?这里有什么问题?
It seems need convert output to numpy array
, for prevent align by index:似乎需要将输出转换为
numpy array
,以防止按索引对齐:
df.loc[0:2,2] = df.loc[2:,2].values
print (df)
0 1 2
0 -0.274583 0.141030 -0.237422
1 -0.887131 -1.253900 -1.347387
2 -0.194082 -0.462745 -1.225560
3 0.095535 0.236268 -1.347387
4 2.210129 -0.816895 -1.225560
Explanation why your solution does not work:解释为什么您的解决方案不起作用:
Output is aligned by index, so if 0,1
indices dont exist add NaN
s:输出按索引对齐,因此如果
0,1
索引不存在添加NaN
s:
print (df.loc[2:,2])
2 -0.237422
3 -1.347387
4 -1.225560
Name: 2, dtype: float64
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.