我想弄清楚是否有一种很好的方法来管理我的熊猫数据中的单位.例如,我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
Run Code Online (Sandbox Code Playgroud)
目前,测量单位以列名编码.缺点包括:
df['width (m)']与df['width']如果我想从列名中删除单位,是否还有其他地方可以存储信息?
chr*_*isb 12
没有任何伟大的方式,现在这样做的权利,请参阅github上的问题在这里进行了一些讨论.
作为一个快速的黑客,可以做这样的事情,维持与单位的单独的dict.
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)'
Run Code Online (Sandbox Code Playgroud)
因为我也在寻找这个。以下是pint和(实验性)pint_pandas今天的功能:
import pandas as pd
import pint
import pint_pandas
ureg = pint.UnitRegistry()
ureg.Unit.default_format = "~P"
pint_pandas.PintType.ureg.default_format = "~P"
df = pd.DataFrame({
"length": pd.Series([1.2, 7.8, 3.4], dtype="pint[m]"),
"width": pd.Series([3.4, 9.0, 5.6], dtype="pint[m]"),
"thickness": pd.Series([5.6, 1.2, 7.8], dtype="pint[cm]"),
})
print(df.pint.dequantify())
Run Code Online (Sandbox Code Playgroud)
length width thickness
unit m m cm
0 1.2 3.4 5.6
1 7.8 9.0 1.2
2 3.4 5.6 7.8
Run Code Online (Sandbox Code Playgroud)
length width thickness
unit m m cm
0 1.2 3.4 5.6
1 7.8 9.0 1.2
2 3.4 5.6 7.8
Run Code Online (Sandbox Code Playgroud)
length width thickness
unit m in cm
0 1.2 133.858268 5.6
1 7.8 354.330709 1.2
2 3.4 220.472441 7.8
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5182 次 |
| 最近记录: |