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

use*_*044 5 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
Run Code Online (Sandbox Code Playgroud)

我收到错误:

AttributeError: ("'str' object has no attribute 'shift'", u'occurred at index 0')
Run Code Online (Sandbox Code Playgroud)

期望的输出:

  Letter  value Previous Value
0      A    one               
1      A    two            one
2      B  three               
3      B   four          three
4      C   five               
Run Code Online (Sandbox Code Playgroud)

EdC*_*ica 6

使用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               
Run Code Online (Sandbox Code Playgroud)