熊猫diff()字符串

2024-05-13 23:16:36 发布

您现在位置:Python中文网/ 问答频道 /正文

如何在每次列更改其字符串值时标记数据帧中的行?

例如:

输入

ColumnA   ColumnB
1            Blue
2            Blue
3            Red
4            Red
5            Yellow


#  diff won't work here with strings....  only works in numerical values
dataframe['changed'] = dataframe['ColumnB'].diff()        


ColumnA   ColumnB      changed
1            Blue         0
2            Blue         0
3            Red          1
4            Red          0
5            Yellow       1

Tags: 数据字符串标记dataframeherewithdiffblue
3条回答

我通过ne而不是使用实际的!=比较获得更好的性能:

df['changed'] = df['ColumnB'].ne(df['ColumnB'].shift().bfill()).astype(int)

计时

使用以下设置生成更大的数据帧:

df = pd.concat([df]*10**5, ignore_index=True) 

我有以下时间安排:

%timeit df['ColumnB'].ne(df['ColumnB'].shift().bfill()).astype(int)
10 loops, best of 3: 38.1 ms per loop

%timeit (df.ColumnB != df.ColumnB.shift()).astype(int)
10 loops, best of 3: 77.7 ms per loop

%timeit df['ColumnB'] == df['ColumnB'].shift(1).fillna(df['ColumnB'])
10 loops, best of 3: 99.6 ms per loop

%timeit (df.ColumnB.ne(df.ColumnB.shift())).astype(int)
10 loops, best of 3: 19.3 ms per loop

使用^{}并比较:

dataframe['changed'] = dataframe['ColumnB'] == dataframe['ColumnB'].shift(1).fillna(dataframe['ColumnB'])

对于我的作品,与^{}相比,则NaN被替换0,因为在没有值之前:

df['diff'] = (df.ColumnB != df.ColumnB.shift()).astype(int)
df.ix[0,'diff'] = 0
print (df)
   ColumnA ColumnB  diff
0        1    Blue     0
1        2    Blue     0
2        3     Red     1
3        4     Red     0
4        5  Yellow     1

timings编辑另一个答案-最快的是使用ne

df['diff'] = (df.ColumnB.ne(df.ColumnB.shift())).astype(int)
df.ix[0,'diff'] = 0

相关问题 更多 >