python - 如何移动多列? Pandas 、 python

标签 python pandas

为简单起见,假设我有这个数据框。

Date           Open    Close
2016-01-01     100     129
2016-01-02     198     193
2016-01-03     103     102
2016-01-04     102     109

我不能说出所有的列名,因为太多了。那么我怎样才能移动除其中两列(日期和关闭)之外的所有列?我想将除 (Date & Close) 之外的所有列移回一行。

Date           Open    Close
2016-01-01     198     129
2016-01-02     103     193
2016-01-03     102     102
2016-01-04     NaN     109

最佳答案

您可以像这样为要排除的列创建掩码:

mask = ~(df.columns.isin(['Date','Close']))

cols_to_shift = df.columns[mask]

df[cols_to_shift] = df.loc[:,mask].shift(-1)

df[cols_to_shift] = df[cols_to_shift].shift(-1)

输出:

         Date   Open  Close
0  2016-01-01  198.0    129
1  2016-01-02  103.0    193
2  2016-01-03  102.0    102
3  2016-01-04    NaN    109

关于python - 如何移动多列? Pandas 、 python ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47490505/

相关文章:

python - 无需转换即可读取日期时间 Pandas

使用 FTP 和列表进行 Python 编程

python - 将列表的元素添加到字典中的固定位置

python - 如何为 groupby DataFrame 创建滚动百分比

python - Pandas 中的日期滞后

Python - 将数据帧保存到 CSV "too many indices for array"错误

python - 从(行、列、值)数据创建 Pandas DataFrame

python - Python 中的 HTTPS session 重用

python - Django Heroku 和 postgresql

python - bcrypt.checkpw 返回 TypeError : Unicode-objects must be encoded before checking