首页 > 解决方案 > 如何将python数据框中一行中的所有元素移动一列?

问题描述

假设我有以下数据框。

   one  two   ...  ten
a  1.0  1.0   ...  1.0
b  2.0  2.0   ...  NaN
c  3.0  3.0   ...  NaN
d  4.0  4.0   ...  4.0

我想在数据帧上进行迭代(也许我不需要?),将最右边一列中带有 Null 的所有行向右移动,以便 NaN 位于第一列。具体来说,我希望所有值都向右移动一个,以便仅覆盖最右侧列中的 NaN。

   one  two   ...  ten
a  1.0  1.0   ...  1.0
b  NaN  2.0   ...  2.0
c  NaN  3.0   ...  3.0
d  4.0  4.0   ...  4.0

感谢您的任何和所有答案,我对编码很陌生,所以我很感激。

标签: pythonpandasdataframe

解决方案


如果我正确理解了您的请求,您可以利用shiftupdate方法,如下所示:

# df

    one     two     ten
a   1.0     1.0     1.0
b   2.0     2.0     NaN
c   3.0     3.0     NaN
d   4.0     4.0     4.0

df.update(
          df.loc[df.iloc[:, -1].isna(), :].shift(axis=1).replace(np.nan, 'na')
)
df.replace('na', np.nan, inplace=True)
print(df)

# Output
    one     two     ten
a   1.0     1.0     1.0
b   NaN     2.0     2.0
c   NaN     3.0     3.0
d   4.0     4.0     4.0

让我们分解一下:

#### Step1: Filter NaN in the last column

df.loc[df.iloc[:, -1].isna(), :]

# Ouput 
    one     two     ten
b   2.0     2.0     NaN
c   3.0     3.0     NaN


#### Step2: Shift the rows to the right

df.loc[df.iloc[:, -1].isna(), :].shift(axis=1)

# Output
    one     two     ten
b   NaN     2.0     2.0
c   NaN     3.0     3.0


#### Step3: Replace NaN with "na"
# This is because the update function doens't replace values with NaN

df.loc[df.iloc[:, -1].isna(), :].shift(axis=1).replace(np.nan, 'na')

# Output
    one     two     ten
b   na      2.0     2.0
c   na      3.0     3.0


#### Step4: Update the orginal dataframe with this new one (in place method)

df.update(df.loc[df.iloc[:, -1].isna(), :].shift(axis=1).replace(np.nan, 'na'))

# Output
    one     two     ten
a   1.0     1.0     1.0
b   na      2.0     2.0
c   na      3.0     3.0
d   4.0     4.0     4.0

#### Step5: Replace back the original NaN

df.replace('na', np.nan, inplace=True)


推荐阅读