【问题标题】:Apply string.format() to row in Pandas DataFrame将 string.format() 应用于 Pandas DataFrame 中的行
【发布时间】:2015-11-28 13:44:18
【问题描述】:

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

假设 pd.DataFrame df 包含“样本”和“日期”列:

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()])

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    您可以只使用行本身。它是一个Series,它支持对项目的类似字典的访问:

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

    【讨论】:

      猜你喜欢
      • 2019-12-25
      • 2018-11-23
      • 2019-04-10
      • 2017-10-22
      • 2020-07-02
      • 1970-01-01
      • 2012-10-14
      • 2018-11-21
      • 2020-02-25
      相关资源
      最近更新 更多