我有以下数据,
公司 | 转 | 每股收益 | 利润 |
---|---|---|---|
c1 | 23.5 | 20.5 | 40.5 |
c2 | 21.5 | 23.5 | 25.5 |
c3 | 40.5 | 32.5 | 20.5 |
我的预期输出是:
公司 | 转 | 每股收益 | 利润 | rev_rank | eps_rank | 利润排名 |
---|---|---|---|---|---|---|
c1 | 23.5 | 20.5 | 40.5 | 2 | 3 | 1 |
c2 | 21.5 | 23.5 | 25.5 | 3 | 2 | 2 |
c3 | 40.5 | 32.5 | 20.5 | 1 | 1 | 3 |
我试过以下输出,
for i8 in list(growth_rank):
'{}'.format(i8)+"_rank"= growth_rank[i8].rank(ascending=False)
growth_rank.append(i8)
它说我不能分配运算符。
如何更改代码?我知道我可以简单地尝试使用以下代码而不是循环,
growth_rank['rev_rank'] = growth_rank['rev'].rank(ascending=False)
但是如何使用循环遍历数据并相应地分配/创建新的排名列?
谢谢
使用f-string
s 分配所有列,而无需首先通过索引选择[1:]
:
for i8 in growth_rank.columns[1:]:
growth_rank[f"{i8}_rank"]= growth_rank[i8].rank(ascending=False).astype(int)
print (growth_rank)
Company rev eps profit rev_rank eps_rank profit_rank
0 c1 23.5 20.5 40.5 2 3 1
1 c2 21.5 23.5 25.5 3 2 2
2 c3 40.5 32.5 20.5 1 1 3
或者在没有首先选择的情况下处理所有列DataFrame.iloc
并将其附加到原始列DataFrame.join
:
df1 = growth_rank.iloc[:, 1:].rank(ascending=False).astype(int).add_suffix('_rank')
df = growth_rank.join(df1)
print (df)
Company rev eps profit rev_rank eps_rank profit_rank
0 c1 23.5 20.5 40.5 2 3 1
1 c2 21.5 23.5 25.5 3 2 2
2 c3 40.5 32.5 20.5 1 1 3
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句