gpt4 book ai didi

python - 如何管理 Pandas 数据中的单位?

转载 作者:行者123 更新时间:2023-12-03 12:57:31 25 4
gpt4 key购买 nike

我想弄清楚是否有一种很好的方法来管理我的 Pandas 数据中的单位。例如,我有一个 DataFrame看起来像这样:

   length (m)  width (m)  thickness (cm)
0 1.2 3.4 5.6
1 7.8 9.0 1.2
2 3.4 5.6 7.8

目前,测量单位以列名称编码。缺点包括:
  • 列选择尴尬-df['width (m)']对比 df['width']
  • 如果我的源数据的单位发生变化,事情可能会中断

  • 如果我想从列名中去除单位,是否还有其他地方可以存储信息?

    最佳答案

    目前没有任何好的方法可以做到这一点,请参阅 github 问题 here进行一些讨论。

    作为一个快速的黑客,可以做这样的事情,用单位维护一个单独的字典。

    In [3]: units = {}

    In [5]: newcols = []
    ...: for col in df:
    ...: name, unit = col.split(' ')
    ...: units[name] = unit
    ...: newcols.append(name)

    In [6]: df.columns = newcols

    In [7]: df
    Out[7]:
    length width thickness
    0 1.2 3.4 5.6
    1 7.8 9.0 1.2
    2 3.4 5.6 7.8

    In [8]: units['length']
    Out[8]: '(m)'

    关于python - 如何管理 Pandas 数据中的单位?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39419178/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com