简体   繁体   English

打印 Pandas 中的特定行,列名和值行明智地使用正确的 dtype

[英]Print a specific row in Pandas with column names and values row wise with the correct dtype

I am trying to print out a specific row in my dataframe with the column names and their respective values for that row.我正在尝试在我的 dataframe 中打印出特定行,其中包含该行的列名及其各自的值。 This is my code.这是我的代码。

import pandas as pd
import numpy as np

df1 = pd.read_csv('mortality_inhospital_dataset1.csv')

df1 = df1.set_index('ID', inplace = False)

df1 = df1.loc[125047]

print(df1.fillna(0).to_string())

I am getting the following output:我得到以下 output:

在此处输入图像描述

My desired output is:我想要的 output 是:

outcome: 0结果:0

age: 72年龄:72

gendera: 0性别:0

BMI: 37.588179体重指数:37.588179

I am not sure why the int values are coming up as floats.我不确定为什么 int 值会以浮点数出现。 Is there a more efficient of presentable way to output this? output 有没有更有效的方法?

The default int dtype does not allow missing values ( nan ), so if one of the rows has missing values, then pandas will encode it as a float .默认的int dtype 不允许缺失值( nan ),因此如果其中一行有缺失值,则pandas会将其编码为float As noted in the comment by @Epsi95, it's best to specify dtypes explicitly:正如@Epsi95 的评论中所述,最好明确指定 dtypes:

dtypes = {"age" : "Int64", "outcome": "Int64"}
cols_to_show = ['outcome', 'age', 'genders', 'BMI']

df1 = pd.read_csv('mortality_inhospital_dataset1.csv', index_col='ID')

df1 = df1.astype(dtypes)

print(df1.loc[125047, cols_to_show])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM