[英]How do I get a series with certain values based on a condition in a dataframe?
I've got a dataframe with a column like this:我有一个 dataframe 有这样的列:
data = {"col": [1, 3, 2, 0, 4, 2, 5, 0, 1, 3, 0]}
df = pd.DataFrame(data)
Out:
col
0 1
1 3
2 2
3 0
4 4
5 2
6 5
7 0
8 1
9 3
10 0
I want to get a Series the same length as that column, with 0's where the data in the column does not equal zero and 100 when it does like below.我想获得一个与该列长度相同的系列,其中列中的数据不等于 0 时为 0,当它如下所示时为 100。 How do I go about this?我该如何 go 关于这个?
0 0
1 0
2 0
3 100
4 0
5 0
6 0
7 100
8 0
9 0
10 100
Compare to 0 and multiply by 100, due to the False/0 and True/1 equivalence this will give 0/100:与 0 比较并乘以 100,由于 False/0 和 True/1 等价,这将得到 0/100:
df['col'].eq(0).mul(100)
output: output:
0 0
1 0
2 0
3 100
4 0
5 0
6 0
7 100
8 0
9 0
10 100
Name: col, dtype: int64
You can use Numpy to Solve this:您可以使用 Numpy 来解决这个问题:
import numpy as np
df['col'] = np.where(df['col'] > 0, 0, 100)
note: if value grater than 0 it return 0 else returns 100注意:如果值大于 0,则返回 0,否则返回 100
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.