我有一個包含許多列的資料框(在這個問題中,我將使用這個資料框的一個示例)并且想要創建新列,當year=2017除以初始列的值時顯示特定列的值。更具體地說,以列price為例。第一個新列price_2017應僅price在 時顯示列的值year=2017。下一列price_ratio應顯示等于 的值price/price_2017。這些_2017和_ratio后綴將添加到除 之外的所有列year。我知道如何手動操作,但是在實際資料集中我有 60 列,因此需要進行一些優化,例如使用loopor apply,但是不知道如何操作。
# importing pandas as pd
import pandas as pd
# dictionary of lists
dict = {'year':[2015, 2016, 2017, 2018],
'price':[1,2,3,4],
'degree': [10,15,22,25],
'score':[90, 40, 80, 98]}
df = pd.DataFrame(dict)
最終資料集應如下所示

uj5u.com熱心網友回復:
將索引設定為year,然后使用loc選擇對應的行2017,然后將資料框除以該行以計算比率并將結果分配回去
s = df.set_index('year')
s.assign(**{**s.loc[2017].add_suffix('_2017'),
**s.div(s.loc[2017]).add_suffix('_ratio')})
結果
price degree score price_2017 degree_2017 score_2017 price_ratio degree_ratio score_ratio
year
2015 1 10 90 3 22 80 0.333333 0.454545 1.125
2016 2 15 40 3 22 80 0.666667 0.681818 0.500
2017 3 22 80 3 22 80 1.000000 1.000000 1.000
2018 4 25 98 3 22 80 1.333333 1.136364 1.225
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/427587.html
