【问题标题】:zip two columns of a dataframe without changing the datatype在不更改数据类型的情况下压缩数据框的两列
【发布时间】:2021-06-11 03:31:33
【问题描述】:

问题很简单。这里我们有一个为列指定数据类型的数据框:

df = pd.DataFrame({'A':[1,2], 'B':[3,4]})
df.A = df.A.astype('int16')

#df
    A   B
0   1   3
1   2   4

#df.dtypes
A    int16
B    int64
dtype: object

现在我将两列 AB 压缩成一个元组:

df['C'] = list(zip(df.A, df.B))

    A   B   C
0   1   3   (1, 3)
1   2   4   (2, 4)

但是,现在C 列中值的数据类型已更改。

type(df.C[0][0])
#int
type(df.A[0])
#numpy.int16

如何压缩两列并将每个值的数据类型保留在元组中,使type(df.C[0][0]) 成为int16(与type(df.A[0]) 相同)?

【问题讨论】:

    标签: python pandas numpy dtype


    【解决方案1】:

    我认为当您引用 df.A 等时会发生一些类型转换。请参阅 https://numpy.org/doc/stable/reference/generated/numpy.ndarray.tolist.html

    将数组数据的副本作为(嵌套)Python 列表返回。数据项 通过 项目功能。

    但这有效

    >>> import pandas as pd
    >>> df = pd.DataFrame({'A':[1,2], 'B':[3,4]})
    >>> df.A = df.A.astype('int16')
    >>> df['C'] = list(zip(df.A.values, df.B.values))
    >>> df
       A  B       C
    0  1  3  (1, 3)
    1  2  4  (2, 4)
    >>> type(df.C[0][0])
    <class 'numpy.int16'>
    >>> type(df.C[0][1])
    <class 'numpy.int64'>
    

    【讨论】:

    • 好点。我认为在较新的版本中.to_numpy().values 更可取。结果是一样的。谢谢。
    猜你喜欢
    • 2016-12-03
    • 1970-01-01
    • 1970-01-01
    • 2019-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多