python - 如何将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
感谢您的任何和所有答案,我对编码很陌生,所以我很感激。
解决方案
如果我正确理解了您的请求,您可以利用shift和update方法,如下所示:
# 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)
推荐阅读
- java - Maven Surefire 插件未通过测试,但 Junit 通过了测试
- python - 在将评论添加为 notnull 时出错
- firebase - Flutter:任务':firebase_core:compileDebugJavaWithJavac'的执行失败
- python - PyInstaller + tkdnd/tkinterdnd2 启动冻结的 exe 时“无法加载 tkdnd 库”。从脚本启动时工作
- json - 无法转换类型“__NSDictionaryI”的值
- node.js - Mongoose 在从 create() 调用时在 pre('save) 中操作文档
- javascript - 在 ReactJS/Javascript 中使用多级数字的树图
- python - OPENCV:添加一个更大的矩形来计数矩形
- powerbi - 为什么我得到不同的总计,但相同的值?
- java - Arquillian 测试的“包不存在”