我试图在pandas数据框上使用shift(),但它没有按照我的期望工作。

问题描述 投票:0回答:1

原始数据框架。

enter image description here

Dafatrame后 df.shift(1, axis=1):

enter image description here

我期望只有一列的移动,而不是两列。

python pandas dataframe shift
1个回答
1
投票

使用@Olivier的示例数据。

import pandas

df = pandas.DataFrame([102, 101, 104, 110, 104, 105])
df = pandas.concat([df, df+10, df+20, df+30], axis=1)
df.columns = ['a', 'b', 'c', 'd']

# this is actually what you have there - discrepancy in types with first column Vs the second one:

df['a']=df['a'].astype(int)
df['b']=df['b'].astype(float)
df['c']=df['c'].astype(float)
df['d']=df['d'].astype(float)

>>> print(df.shift(1, axis=1))

    a   b      c      d
0 NaN NaN  112.0  122.0
1 NaN NaN  111.0  121.0
2 NaN NaN  114.0  124.0
3 NaN NaN  120.0  130.0
4 NaN NaN  114.0  124.0
5 NaN NaN  115.0  125.0

# Mitigation:

df=df.astype(float)

>>> print(df.shift(1, axis=1))

    a      b      c      d
0 NaN  102.0  112.0  122.0
1 NaN  101.0  111.0  121.0
2 NaN  104.0  114.0  124.0
3 NaN  110.0  120.0  130.0
4 NaN  104.0  114.0  124.0
5 NaN  105.0  115.0  125.0

0
投票

发布代码确实比较容易.请把这段代码作为例子:

import pandas

df = pandas.DataFrame([102, 101, 104, 110, 104, 105])
df = pandas.concat([df, df+10, df+20, df+30], axis=1)
df.columns = ['a', 'b', 'c', 'd']
print(df)

print(df.shift(1, axis=1))

输出:

     a    b    c    d
0  102  112  122  132
1  101  111  121  131
2  104  114  124  134
3  110  120  130  140
4  104  114  124  134
5  105  115  125  135
    a      b      c      d
0 NaN  102.0  112.0  122.0
1 NaN  101.0  111.0  121.0
2 NaN  104.0  114.0  124.0
3 NaN  110.0  120.0  130.0
4 NaN  104.0  114.0  124.0
5 NaN  105.0  115.0  125.0
© www.soinside.com 2019 - 2024. All rights reserved.