下表对文本中的唯一单词进行了计数(在本例中为 Hamlet 的德文文本)。
我想使用 Pandas 添加一列 ['frequency'] 来打印三个答案之一。
如果“计数”列中的值 <=10,则频率为 “不常见”
如果“计数”列中的值>10,则频率为 '经常'
如果“计数”列中的值为 1,则频率为“唯一”
我是 pandas 的新手,所以我最初认为我必须使用“for”循环和“if”“else”。当然,这对我不起作用,在阅读了这篇文章之后,我发现您可以改用 .loc[] 。它更干净。
我会把答案放在下面,以防其他人非常清楚地需要这个设置。 🙂 这是我之前使用的表格-
count word length
0 67223 0
1 7 deinen 6
2 1 überwachsen 11
3 3 them 4
4 2 fortunens 9
5 1 flammen 7
6 1 ersäuentsezlichen 17
7 2 alleino 7
8 1 empfehle 8
9 1 beschulöffentlicher 19
10 1 unterthänige 12
11 1 pr 2
12 1 zurükzutreiben 14
13 38 wo 2
14 1 schadhaften 11
15 1 ddiese 6
16 1 zurükhaltend 12
17 1 laim 4
18 1 agents 6
最佳答案
这是 pd.cut
的绝佳用例:
pd.cut(df['count'],
bins=[-np.inf, 1, 10, np.inf],
labels=['unique', 'infrequent', 'frequent'])
0 frequent
1 infrequent
2 unique
3 infrequent
4 infrequent
5 unique
6 unique
7 infrequent
8 unique
9 unique
10 unique
11 unique
12 unique
13 frequent
14 unique
15 unique
16 unique
17 unique
18 unique
Name: count, dtype: category
Categories (3, object): [unique < infrequent < frequent]
另一个答案中 np.select
的缺点是您需要在选择之前评估所有条件,并且不能随着条件的增加而扩展。
关于python - Pandas 相当于 'if' 'else' 条件将计算列添加到 df,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53970328/