首页 文章

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

提问于
浏览
2

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

假设 pd.DataFrame df 列'specimen'和'date':

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

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

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

更新:

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

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

1 回答

  • 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'
    

相关问题