我想采用以下数据帧(df):
Team Group1 Group2 Group3
green 1 5 -6
blue -3 10 5
red -7 9 -8
并仅对Group1:Group3列应用此格式:
DF = '{0:,.0f}'.format(x) if x > 0 else '({0:,.0f})'.format(abs(x)) for x in DF
或使用def,我似乎无法使语法正确:
def formatting(x):
if i > 0:
'{0:,.0f}'.format(x)
else:
'({0:,.0f})'.format(abs(x))
DF.applymap(formatting)
预期的输出是这样的:
Team Group1 Group2 Group3
green 1 5 (6)
blue (3) 10 5
red (7) 9 (8)
提前谢谢!
答案 0 :(得分:3)
在Python 3.6+中,您可以使用格式化的字符串文字,也称为f-strings:
def formatter(x):
return str(x) if x >= 0 else f'({abs(x)})'
for col in df.columns[1:]:
df[col] = df[col].apply(formatter)
print(df)
Team Group1 Group2 Group3
0 green 1 5 (6)
1 blue (3) 10 5
2 red (7) 9 (8)