在apply函数中使用shift()函数来比较Pandas Dataframe中的行

时间:2016-06-22 11:43:54

标签: python python-2.7 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               

2 个答案:

答案 0 :(得分:5)

在使用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               

答案 1 :(得分:2)

您正尝试将.shift()应用于给定行的给定列的值而不是Series。我会这样做,使用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