pandas 的 DataFrame 矩阵数据对象如何根据某列的条件给另一个指定列进行赋值?
推荐方案
使用 DataFrame 对象的 loc
函数,具体如下示例:
import pandas as pd
data = {
'Team': ['Riders', 'Riders', 'Devils', 'Devils', 'Kings', 'kings', 'Kings', 'Kings', 'Riders', 'Royals', 'Royals',
'Riders'],
'Rank': [1, 2, 2, 3, 3, 4, 1, 1, 2, 4, 1, 2],
'Year': [2014, 2015, 2014, 2015, 2014, 2015, 2016, 2017, 2016, 2014, 2015, 2017],
'Points': [876, 789, 863, 673, 741, 812, 756, 788, 694, 701, 804, 690]
}
df = pd.DataFrame(data)
print(df)
df.loc[df['Team'] == 'Riders', 'Points'] = 1000
print(df)
将 Team 列等于 'Riders' 的 Points 列设置值为 1000,输出如下:
Team Rank Year Points 0 Riders 1 2014 876 1 Riders 2 2015 789 2 Devils 2 2014 863 3 Devils 3 2015 673 4 Kings 3 2014 741 5 kings 4 2015 812 6 Kings 1 2016 756 7 Kings 1 2017 788 8 Riders 2 2016 694 9 Royals 4 2014 701 10 Royals 1 2015 804 11 Riders 2 2017 690 Team Rank Year Points 0 Riders 1 2014 1000 1 Riders 2 2015 1000 2 Devils 2 2014 863 3 Devils 3 2015 673 4 Kings 3 2014 741 5 kings 4 2015 812 6 Kings 1 2016 756 7 Kings 1 2017 788 8 Riders 2 2016 1000 9 Royals 4 2014 701 10 Royals 1 2015 804 11 Riders 2 2017 1000