Answers:
您需要选择该列:
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)> ]
编辑
如果你想生成一个布尔值指标,那么你可以只使用布尔条件产生boolean值系列和铸铁的D型到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'])
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()
。我想做的基本上是df['A'] = np.where(df['B'] in some_values, df['A']*2, df['A]
。有人对此有想法吗?
对于单一条件,即。 ( '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'])