将string.format()应用于Pandas DataFrame中的行

Mik*_*ike 3 python pandas

我想在一个pandas DataFrame中用一个引用列的格式化字符串表示一行.我找到的最好的方法是将行转换为dict然后string.format()

假设有一个pd.DataFrame df列'标本'和'日期':

r = df.loc[0]
print("{specimen}_{date}".format(**r.to_dict()))
Run Code Online (Sandbox Code Playgroud)

可用于使用列数据应用格式字符串.

这看起来效率不高.是否必须有更好的方法在pandas中直接执行此操作而不转换为dict,同时保持格式化字符串中显式命名列的灵活性?

更新:

最终目的是为matplotlib图生成刻度标签.使用以下答案:

plot.set_yticklabels(["{specimen}_{date}".format(**r) for i,r in df.iterrows()])
Run Code Online (Sandbox Code Playgroud)

Bre*_*arn 6

你可以只使用行本身.它Series支持对项目的类似dict的访问:

>>> d
   A     B      C
0  1  This    One
1  2    is    Two
2  3  crud  Three
>>> "{A} then {B} and also {C}".format(**d.iloc[0])
'1 then This and also One'
Run Code Online (Sandbox Code Playgroud)