Skip to content

Converting a pint.Quantity to PintArray when adding to a pd.DataFrame #248

@Musaefendic

Description

@Musaefendic

Description

I tried adding a pint.Quantity to an existing pd.DataFrame, thinking that pint-pandas might transform the Quantity into a PintArray that:

  • matches the number of rows
  • preserves the unit.

Reproducible Example

import pandas as pd
from pint_pandas import PintArray, Quantity

# Existing pd.DataFrame
data = {"bar": [0.07, 0.30, 0.85, 1.00]}
df = pd.DataFrame(data)

# Trying to add a `pint.Quantity`
df['content'] = Quantity(42.0, units='percent')

df.dtypes 

# Output:
# bar      float64
# content  object    # <---- Expected: pint[percent]

output:

bar content
0 0.07 42.0 percent
1 0.30 42.0 percent
2 0.85 42.0 percent
3 1.00 42.0 percent

Question

The documentation indeed suggests using a pd.Series or a PintArray to achieve this, but this approach feels a bit verbose. I’d like to add a new column directly with just Quantity to mimic the pandas API when creating a new column from a float to an existing pd.DataFrame.

Would it make sense to convert a pint.Quantity into a PintArray when adding it to a pd.DataFrame?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions