[英]Replace specific values in pandas dataframe with the corresponding column name, based on a condition,
[英]Pandas DataFrame: replace all values in a column, based on condition
我有一个简单的 DataFrame,如下所示:
我想从“第一季”列中选择所有值,并将 1990 年以上的值替换为 1。在此示例中,只有巴尔的摩乌鸦队会将 1996 年替换为 1(保持其余数据不变)。
我使用了以下内容:
df.loc[(df['First Season'] > 1990)] = 1
但是,它将该行中的所有值替换为 1,而不仅仅是“第一季”列中的值。
如何仅替换该列中的值?
您需要选择该列:
In [41]:
df.loc[df['First Season'] > 1990, 'First Season'] = 1
df
Out[41]:
Team First Season Total Games
0 Dallas Cowboys 1960 894
1 Chicago Bears 1920 1357
2 Green Bay Packers 1921 1339
3 Miami Dolphins 1966 792
4 Baltimore Ravens 1 326
5 San Franciso 49ers 1950 1003
所以这里的语法是:
df.loc[<mask>(here mask is generating the labels to index) , <optional column(s)> ]
您可以查看文档以及显示语义的10 分钟到 Pandas
编辑
如果你想生成一个布尔指标,那么你可以只使用布尔条件来生成一个布尔系列并将 dtype 转换为int
这将分别将True
和False
转换为1
和0
:
In [43]:
df['First Season'] = (df['First Season'] > 1990).astype(int)
df
Out[43]:
Team First Season Total Games
0 Dallas Cowboys 0 894
1 Chicago Bears 0 1357
2 Green Bay Packers 0 1339
3 Miami Dolphins 0 792
4 Baltimore Ravens 1 326
5 San Franciso 49ers 0 1003
聚会有点晚了,但仍然 - 我更喜欢使用 numpy ,其中:
import numpy as np
df['First Season'] = np.where(df['First Season'] > 1990, 1, df['First Season'])
df['First Season'].loc[(df['First Season'] > 1990)] = 1
奇怪的是没有人有这个答案,你的代码唯一缺少的部分是 df 之后的 ['First Season'] ,只需删除里面的大括号。
df.loc[df['First season'] > 1990, 'First Season'] = 1
解释:
df.loc
有两个参数,“行索引”和“列索引”。 我们正在检查“第一季”列下每行值的值是否大于 1990,然后将其替换为 1。
对于单一条件,即。 ( 'employrate'] > 70 )
country employrate alcconsumption
0 Afghanistan 55.7000007629394 .03
1 Albania 51.4000015258789 7.29
2 Algeria 50.5 .69
3 Andorra 10.17
4 Angola 75.6999969482422 5.57
用这个:
df.loc[df['employrate'] > 70, 'employrate'] = 7
country employrate alcconsumption
0 Afghanistan 55.700001 .03
1 Albania 51.400002 7.29
2 Algeria 50.500000 .69
3 Andorra nan 10.17
4 Angola 7.000000 5.57
因此这里的语法是:
df.loc[<mask>(here mask is generating the labels to index) , <optional column(s)> ]
对于多个条件,即。 (df['employrate'] <=55) & (df['employrate'] > 50)
用这个:
df['employrate'] = np.where(
(df['employrate'] <=55) & (df['employrate'] > 50) , 11, df['employrate']
)
out[108]:
country employrate alcconsumption
0 Afghanistan 55.700001 .03
1 Albania 11.000000 7.29
2 Algeria 11.000000 .69
3 Andorra nan 10.17
4 Angola 75.699997 5.57
因此这里的语法是:
df['<column_name>'] = np.where((<filter 1> ) & (<filter 2>) , <new value>, df['column_name'])
我们可以使用以下语法更新 df 中的 First Season 列:
df['First Season'] = expression_for_new_values
要映射 First Season 中的值,我们可以使用 pandas 的 .map() 方法和以下语法:
data_frame(['column']).map({'initial_value_1':'updated_value_1','initial_value_2':'updated_value_2'})
另一种选择是使用列表理解:
df['First Season'] = [1 if year > 1990 else year for year in df['First Season']]
df.First Season.loc[(df['First Season'] > 1990)] = 1
df["First season"] = df["First season"].apply(lambda x : 1 if x > 1990 else x)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.