我有一个分组和聚合的数据框
df_subsegment:
segment Sales Income Rent
0 A 184.37 224.24 5242.9
1 B 45.42 176.79 6693.0
<+100 rows>
我已经从上述数据框中创建了一个列表:
SubSegment_list = df_subsegment['segment'].unique()
SubSegment_list
[out] array(['A', 'B'], dtype=object)
for i in SubSegment_list:
var1 = df['Sales']
var2 = df['Income']
var3 = df['Rent']
flag1 = 'up' if var1>0 else 'down'
flag2 = 'up' if var2>0 else 'down'
flag3 = 'leverage' if var3>0 else 'deleverage'
print(f"{SubSegment_list[0]} Sales {flag1} {round(var1)} % vs LY while Total income {flag2} {var2}% vs LY creating {flag3}")
让我们考虑一下,上面提到的列表现在只有2个值,即A和B。然后从此for循环中萌发的输出包含两个语句,但是它们都具有相同的值,如下所示:
A Sales up 184 % vs LY while Total income up 224.24% vs LY creating leverage
A Sales up 184 % vs LY while Total income up 224.24% vs LY creating leverage
如何考虑每行的数据生成两个唯一的语句,如下所示:
预期输出:
A Sales up 184% vs LY while Total income up 224.24% vs LY creating leverage
B Sales up 45% vs LY while Total income up 176.79% vs LY creating leverage
答案 0 :(得分:3)
您可以使用iterrows
:
for _, value in df.iterrows():
var1 = value['Sales']
var2 = value['Income']
seg1 = value['segment']
flag1 = 'up' if var1>0 else 'down'
flag2 = 'up' if var2>0 else 'down'
print(f"{seg1} Sales {flag1} {var1}% vs LY while Total income {flag2} {var2}% vs LY creating leverage")
A Sales up 184.37% vs LY while Total income up 224.24% vs LY creating leverage
B Sales up 45.42% vs LY while Total income up 176.79% vs LY creating leverage