
本教程旨在解决pandas dataframe中新增列(如'total'列或索引转换为列后)在`df.info()`输出中不显示的问题。核心原因通常是代码执行顺序不当,即在列创建前调用了`info()`,或未将索引显式转换为列。文章将详细阐述这些问题,并提供基于`reset_index()`和正确执行顺序的解决方案,确保所有期望的列都能在`df.info()`中正确呈现,从而便于后续数据分析与可视化。
在使用Pandas进行数据分析时,我们经常需要向DataFrame中添加新的列,例如计算总和列。然而,有时即使新列在DataFrame的显示输出中清晰可见,但在调用df.info()时,这些新列却未能出现在输出的列列表中。同样,DataFrame的索引列(如示例中的'A', 'B', 'C', 'D')在默认情况下也不会被df.info()识别为数据列。本文将深入探讨这些现象背后的原因,并提供切实可行的解决方案。
假设我们有一个DataFrame df,包含 'H1', 'H2', 'H3' 三列。我们通过以下代码添加了一个 'Total' 列:
import pandas as pd
import numpy as np
# 示例数据
data = {
'H1': [1.643910e+10, 3.876800e+09, 2.126470e+10, 3.911600e+09],
'H2': [5.403600e+09, 1.056970e+10, 1.077500e+09, 3.309300e+09],
'H3': [1.090100e+09, 6.152400e+09, 2.858000e+08, 8.170000e+07]
}
index_labels = ['A', 'B', 'C', 'D']
df = pd.DataFrame(data, index=index_labels)
# 添加 'Total' 列
df['Total'] = df[list(df.columns)].sum(axis=1)
print("DataFrame显示:")
print(df)输出的DataFrame将正确显示 'Total' 列:
DataFrame显示:
H1 H2 H3 Total
A 1.643910e+10 5.403600e+09 1.090100e+09 2.293280e+10
B 3.876800e+09 1.056970e+10 6.152400e+09 2.059890e+10
C 2.126470e+10 1.077500e+09 2.858000e+08 2.262800e+10
D 3.911600e+09 3.309300e+09 8.170000e+07 7.302600e+09然而,当我们执行 df.info() 时,却可能得到以下结果,其中 'Total' 列和索引列并未显示:
print("\ndf.info()输出:")
df.info()df.info()输出: <class 'pandas.core.frame.DataFrame'> Index: 4 entries, A to D Data columns (total 3 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 H1 4 non-null float64 1 H2 4 non-null float64 2 H3 4 non-null float64 dtypes: float64(3) memory usage: 256.0+ bytes
这种现象主要由以下两个原因造成:
df.info() 方法会打印出DataFrame在调用那一刻的结构信息。如果我们在创建 'Total' 列的代码执行之前就调用了 df.info(),那么它自然不会包含尚未创建的列。即使之后再创建了列,df.info() 的输出也不会自动更新。
解决方案:
确保在所有列创建和修改操作完成后再调用 df.info()。在交互式开发环境(如Jupyter Notebook或IPython)中,如果遇到此问题,最直接的解决办法是:
正确执行顺序示例:
import pandas as pd
import numpy as np
# 示例数据
data = {
'H1': [1.643910e+10, 3.876800e+09, 2.126470e+10, 3.911600e+09],
'H2': [5.403600e+09, 1.056970e+10, 1.077500e+09, 3.309300e+09],
'H3': [1.090100e+09, 6.152400e+09, 2.858000e+08, 8.170000e+07]
}
index_labels = ['A', 'B', 'C', 'D']
df = pd.DataFrame(data, index=index_labels)
# 确保在调用 info() 之前创建 'Total' 列
df['Total'] = df[list(df.columns)].sum(axis=1)
# 现在调用 info(),'Total' 列将显示
print("\n正确执行顺序后的 df.info() 输出:")
df.info()此时 df.info() 的输出将包含 'Total' 列:
正确执行顺序后的 df.info() 输出: <class 'pandas.core.frame.DataFrame'> Index: 4 entries, A to D Data columns (total 4 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 H1 4 non-null float64 1 H2 4 non-null float64 2 H3 4 non-null float64 3 Total 4 non-null float64 dtypes: float64(4) memory usage: 288.0+ bytes
DataFrame的索引(如示例中的 'A', 'B', 'C', 'D')在Pandas中是一个特殊的结构,它不是普通的数据列。因此,df.info() 默认不会将其列为数据列。如果需要将索引作为一列进行分析或可视化,需要将其显式转换为数据列。
解决方案:
使用 df.reset_index() 方法可以将DataFrame的索引重置为默认的整数索引,并将原有的索引转换为一个名为 'index'(或自定义名称)的普通数据列。
# 将索引转换为数据列
df_reset = df.reset_index()
print("\nreset_index() 后的 DataFrame 显示:")
print(df_reset)
print("\nreset_index() 后的 df.info() 输出:")
df_reset.info()输出结果将显示 'index' 列:
reset_index() 后的 DataFrame 显示: index H1 H2 H3 Total 0 A 1.643910e+10 5.403600e+09 1.090100e+09 2.293280e+10 1 B 3.876800e+09 1.056970e+10 6.152400e+09 2.059890e+10 2 C 2.126470e+10 1.077500e+09 2.858000e+08 2.262800e+10 3 D 3.911600e+09 3.309300e+09 8.170000e+07 7.302600e+09 reset_index() 后的 df.info() 输出: <class 'pandas.core.frame.DataFrame'> RangeIndex: 4 entries, 0 to 3 Data columns (total 5 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 index 4 non-null object 1 H1 4 non-null float64 2 H2 4 non-null float64 3 H3 4 non-null float64 4 Total 4 non-null float64 dtypes: float64(4), object(1) memory usage: 288.0+ bytes
注意事项:
在原始问题中提到了 inplace=True。需要明确的是,当我们通过直接赋值的方式 df['新列名'] = ... 来创建或修改列时,Pandas会直接在原DataFrame上进行操作,因此不需要也不应使用 inplace=True。这个参数主要用于那些会返回新DataFrame的方法(例如 drop(), fillna(), set_index() 等),以指示它们直接修改原DataFrame而不是返回一个副本。
要确保Pandas DataFrame中的所有期望列(包括新增列和作为数据列的索引)都能在 df.info() 中正确显示,关键在于理解DataFrame的状态和操作的执行顺序:
通过遵循这些原则,您可以更准确地理解和调试DataFrame的结构,为后续的数据分析和可视化工作奠定坚实的基础。如果需要快速检查数值列的统计信息,df.describe() 也是一个有用的工具,它会自动包含所有数值类型的列。
以上就是解决Pandas DataFrame新增列在info()中不显示的问题的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号