Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/362.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 对于数据帧中具有NaN的任何行,按1移位_Python_Pandas - Fatal编程技术网

Python 对于数据帧中具有NaN的任何行,按1移位

Python 对于数据帧中具有NaN的任何行,按1移位,python,pandas,Python,Pandas,这是我的输出 from pandas import DataFrame from numpy.random import randn df = DataFrame(randn(5, 3), index=['a', 'c', 'e', 'f', 'h'], columns=['one', 'two', 'three']) df2 = df.reindex(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']) df2['one']['i'] = 5 我想弄

这是我的输出

from pandas import DataFrame
from numpy.random import randn

df = DataFrame(randn(5, 3), index=['a', 'c', 'e', 'f', 'h'], columns=['one', 'two', 'three'])
df2 = df.reindex(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'])
df2['one']['i'] = 5
我想弄清楚的是,对于最后一行中有NaN的列(这是第I行,我想将这些列移动1)

现在,我正在做
df2['two'].shift(1)
df2['two'].shift(1)
,但是有没有一种我没有的推荐的编码方法


所以我得到了
df2[-1:]
作为最后一个索引。。。但我有点困在这里了

也许有一种方法可以减少重复,但无论如何,下面的方法应该是可行的。首先,找出需要移位的列,然后用移位的版本替换这些列

        one       two     three
a -1.132283 -1.204504 -0.763302
b       NaN       NaN       NaN
c  1.778895 -1.931615 -0.040319
d       NaN       NaN       NaN
e  0.612546 -0.846982  0.524779
f -0.527883  0.342746 -0.010093
g       NaN       NaN       NaN
h -0.636055 -0.909910  0.642658
i  5.000000       NaN       NaN

获取最后一行:

to_shift = pd.isnull(df2.iloc[-1])
df2.loc[:,to_shift] = df2.loc[:,to_shift].shift(1)
查看丢失数据的位置:

>>> df2.iloc[-1]
one       5
two     NaN
three   NaN
Name: i, dtype: float64
选择框架的该部分:

>>> pd.isnull(df2.iloc[-1])
one      False
two       True
three     True
Name: i, dtype: bool
>>> to_shift = pd.isnull(df2.iloc[-1])
移动它:

>>> df2.loc[:, to_shift]
        two     three
a -0.447225  0.240786
b       NaN       NaN
c  1.736224  0.191835
d       NaN       NaN
e -0.310505  2.121659
f  2.542979 -0.772117
g       NaN       NaN
h -0.350395  0.825386
i       NaN       NaN
并用移位的数据填充帧:

>>> df2.loc[:, to_shift].shift(1)
        two     three
a       NaN       NaN
b -0.447225  0.240786
c       NaN       NaN
d  1.736224  0.191835
e       NaN       NaN
f -0.310505  2.121659
g  2.542979 -0.772117
h       NaN       NaN
i -0.350395  0.825386

非常感谢你!这对我来说非常有效,而且非常简单。
>>> df2.loc[:, to_shift] = df2.loc[:, to_shift].shift(1)
>>> df2
        one       two     three
a -0.691010       NaN       NaN
b       NaN -0.447225  0.240786
c  0.570639       NaN       NaN
d       NaN  1.736224  0.191835
e  2.509598       NaN       NaN
f -2.053269 -0.310505  2.121659
g       NaN  2.542979 -0.772117
h  1.812492       NaN       NaN
i  5.000000 -0.350395  0.825386