打印数据框时,如何在标题中包含列类型?

2024-04-28 15:10:17 发布

您现在位置:Python中文网/ 问答频道 /正文

如何将仅打印数据框的功能与DataFrame.dtypes结合起来

例如,不只是进行打印(df)并获取:

      animal age
0  alligator 12
1        bee 13
2     falcon 1
3       lion 15
4     monkey 14
5     parrot 44
6      shark 100
7      whale 200
8      zebra 14

我会得到:

      animal (string) age (int64)
0  alligator          12
1        bee          13
2     falcon          1
3       lion          15
4     monkey          14
5     parrot          44
6      shark          100
7      whale          200
8      zebra          14

我正在网上学习一个教程,希望看到前后表的结构


Tags: 数据功能dataframeagemonkeyparrotbeefalcon
2条回答

首先注意,数据类型不一定反映Python内置类型。例如,没有strdtype这样的东西。在Pandas中,字符串存储在objectdtype系列中,表示指向任意对象的指针

您可以使用列表理解并指定给列:

df.columns = [f'{col} ({col_type})' for col, col_type in zip(df, df.dtypes)]

print(df)

  animal (object)  age (int64)
0       alligator           12
1             bee           13
2          falcon            1
3            lion           15
4          monkey           14
5          parrot           44
6           shark          100
7           whale          200
8           zebra           14

对于您的用例,只需打印df.dtypes就足够了

您可以使用zipdf.dtypes将列标题重命名为元组:

df.columns=list(zip(df.columns, df.dtypes))

请注意,字符串列的数据类型不是“字符串”,而是“对象”

相关问题 更多 >