pandas 基于过滤器更改数据框列的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38876816/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 01:47:05  来源:igfitidea点击:

Change Value of a Dataframe Column Based on a Filter

pythonpandasdataframe

提问by anc1revv

I have a Dataframe that consists of 2 columns:

我有一个由 2 列组成的数据框:

  1. "Time Spent on website"
  2. "Dollars spent on the website"
  1. “在网站上花费的时间”
  2. “在网站上花费的美元”

I want to perform some classification analysis on this dataset and I only care whether a user made a purchase or not. So I want to run through the "Dollars spent on the website" column and transform the value to "1" if the user spent over $0.00 and have the value be "0" if the user spent nothing.

我想对这个数据集进行一些分类分析,我只关心用户是否进行了购买。因此,我想遍历“在网站上花费的美元”列,如果用户花费超过 0.00 美元,则将值转换为“1”,如果用户什么都没花,则将值转换为“0”。

What is the proper way to do this with a pandas dataframe?

使用Pandas数据框执行此操作的正确方法是什么?

回答by SO44

df['purchase'] = 0
df.loc[df['dollars_spent'] > 0, 'purchase'] = 1

or

或者

df['purchase'] = df['dollars_spent'].apply(lambda x: 1 if x > 0 else 0)