在应用功能中使用Shift()函数在PANDAS数据框架中比较行



我想使用 shift()从上一个索引中摘取数据,在其中一列中提供的值Letter是相同的。

import pandas as pd
df = pd.DataFrame(data=[['A', 'one'],
                        ['A', 'two'],
                        ['B', 'three'],
                        ['B', 'four'],
                        ['C', 'five']],
                  columns=['Letter', 'value'])
df['Previous Value'] = df.apply(lambda x : x['value'] if x['Letter'].shift(1) == x['Letter'] else "", axis=1)
print df

我遇到了错误:

AttributeError: ("'str' object has no attribute 'shift'", u'occurred at index 0')

所需的输出:

  Letter  value Previous Value
0      A    one               
1      A    two            one
2      B  three               
3      B   four          three
4      C   five               

在您的条件上使用where,其中当前行使用shift匹配上一行:

In [11]:
df = pd.DataFrame(data=[['A', 'one'],
                        ['A', 'two'],
                        ['B', 'three'],
                        ['B', 'four'],
                        ['C', 'five']],
                  columns=['Letter', 'value'])
​
df['Previous Value'] = df['value'].shift().where(df['Letter'].shift() == df['Letter'], '')
df
​
Out[11]:
  Letter  value Previous Value
0      A    one               
1      A    two            one
2      B  three               
3      B   four          three
4      C   five               

您试图将.shift()应用于给定行的给定列的值而不是系列。我会使用Groupby:

这样做
In [6]: df['Previous letter'] = df.groupby('Letter').value.shift()
In [7]: df
Out[7]:
  Letter  value Previous letter
0      A    one             NaN
1      A    two             one
2      B  three             NaN
3      B   four           three
4      C   five             NaN

最新更新