简体   繁体   English

如何根据 dataframe 中的条件获得具有特定值的系列?

[英]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.

相关问题 如何根据特定条件删除 Pandas DataFrame 的行? - How do I remove rows of a Pandas DataFrame based on a certain condition? 如何在满足数据框中条件的行中提取某些值? - How do i extract certain values in a row satisfying a condition in a dataframe? 如何根据另一列的日期条件获取熊猫数据框中特定列的值? - How do I get the values of a particular column in a pandas dataframe based on a date condition on another column? 如何根据某些值获取 DataFrame 中组的最后一行? - How do I get the last row of a group in a DataFrame based on certain values? 如何根据 dataframe 中的条件计算字符串值的出现次数? - How do I count the occurrence of string values based on a condition in a dataframe? 如何在给定特定条件下更改 dataframe 列值 - How do I change the dataframe column values given certain condition(s) 如何在条件下替换数据框的值 - How do i replace the values of a dataframe on a condition 如何根据条件更改pandas系列中的值 - How do I change value in a pandas series based on condition 如何根据日期条件使用另一个 dataframe 填充缺失值,但形状不同? - How do I fill in missing values using another dataframe based on date condition, but which are different shapes? 如何根据所述DataFrame中的另一个系列将布尔系列添加到python DataFrame中? - How do I add a boolean series to a python DataFrame based on another series in said DataFrame?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM