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)
使用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)
归档时间: |
|
查看次数: |
6028 次 |
最近记录: |