在Pandas DataFrame中的if-then-else块中评估多个条件 [英] Evaluating multiple conditions in if-then-else block in a Pandas DataFrame
问题描述
我想通过评估if-then-else块中的多个条件在Pandas DataFrame中创建一个新列。
I want to create a new column in a Pandas DataFrame by evaluating multiple conditions in an if-then-else block.
if events.hour <= 6:
events['time_slice'] = 'night'
elif events.hour <= 12:
events['time_slice'] = 'morning'
elif events.hour <= 18:
events['time_slice'] = 'afternoon'
elif events.hour <= 23:
events['time_slice'] = 'evening'
运行此命令时,出现以下错误:
When I run this, I get the error below:
ValueError:系列的真值不明确。使用a.empty,a.bool(),a.item(),a.any()或a.all()。
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
因此,我尝试通过添加如下所示的任何语句来解决此问题:
So I tried to solve this by adding the any statement like shown below:
if (events.hour <= 6).any():
events['time_slice'] = 'night'
elif (events.hour <= 12).any():
events['time_slice'] = 'morning'
elif (events.hour <= 18).any():
events['time_slice'] = 'afternoon'
elif (events.hour <= 23).any():
events['time_slice'] = 'evening'
现在不会出现任何错误,但是当我检查time_slice的唯一值时,它仅显示'night'
Now I do not get any error, but when I check the unique values of time_slice, it only shows 'night'
np.unique(events.time_slice)
array(['night'],dtype =对象)
array(['night'], dtype=object)
我该如何解决这个问题,因为我的数据中包含的样本应该会出现上午,下午或晚上 。谢谢!
How can I solve this, because my data contains samples that should get 'morning', 'afternoon' or 'evening'. Thanks!
推荐答案
您可以使用 pd.cut()方法,以便对数据进行分类:
you can use pd.cut() method in order to categorize your data:
演示:
In [66]: events = pd.DataFrame(np.random.randint(0, 23, 10), columns=['hour'])
In [67]: events
Out[67]:
hour
0 5
1 17
2 12
3 2
4 20
5 22
6 20
7 11
8 14
9 8
In [71]: events['time_slice'] = pd.cut(events.hour, bins=[-1, 6, 12, 18, 23], labels=['night','morning','afternoon','evening'])
In [72]: events
Out[72]:
hour time_slice
0 5 night
1 17 afternoon
2 12 morning
3 2 night
4 20 evening
5 22 evening
6 20 evening
7 11 morning
8 14 afternoon
9 8 morning
这篇关于在Pandas DataFrame中的if-then-else块中评估多个条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!