pandas中关于DataFrame行,列显示不完全(省略)的解决办法

本文介绍如何通过调整Pandas库的显示选项来完整展示DataFrame的内容,包括所有行和列,并设置值的最大显示长度。

有时候DataFrame中的行列数量太多,print打印出来会显示不完全。就像下图这样:

列显示不全:

这里写图片描述

行显示不全:

这里写图片描述

添加如下代码,即可解决。

#显示所有列
pd.set_option('display.max_columns', None)
#显示所有行
pd.set_option('display.max_rows', None)
#设置value的显示长度为100,默认为50
pd.set_option('max_colwidth',100)

根据自己的需要更改相应的设置即可。

ps:set_option()的所有属性:

Available options:

- display.[chop_threshold, colheader_justify, column_space, date_dayfirst,
  date_yearfirst, encoding, expand_frame_repr, float_format, height, large_repr]
- display.latex.[escape, longtable, repr]
- display.[line_width, max_categories, max_columns, max_colwidth,
  max_info_columns, max_info_rows, max_rows, max_seq_items, memory_usage,
  mpl_style, multi_sparse, notebook_repr_html, pprint_nest_depth, precision,
  show_dimensions]
- display.unicode.[ambiguous_as_wide, east_asian_width]
- display.[width]
- io.excel.xls.[writer]
- io.excel.xlsm.[writer]
- io.excel.xlsx.[writer]
- io.hdf.[default_format, dropna_table]
- mode.[chained_assignment, sim_interactive, use_inf_as_null]

Parameters
----------
pat : str
    Regexp which should match a single option.
    Note: partial matches are supported for convenience, but unless you use the
    full option name (e.g. x.y.z.option_name), your code may break in future
    versions if new options with similar names are introduced.
value :
    new value of option.

Returns
-------
None

Raises
------
OptionError if no such option exists

Notes
-----
The available options with its descriptions:

display.chop_threshold : float or None
    if set to a float value, all float values smaller then the given threshold
    will be displayed as exactly 0 by repr and friends.
    [default: None] [currently: None]

display.colheader_justify : 'left'/'right'
    Controls the justification of column headers. used by DataFrameFormatter.
    [default: right] [currently: right]

display.column_space No description available.
    [default: 12] [currently: 12]

display.date_dayfirst : boolean
    When True, prints and parses dates with the day first, eg 20/01/2005
    [default: False] [currently: False]

display.date_yearfirst : boolean
    When True, prints and parses dates with the year first, eg 2005/01/20
    [default: False] [currently: False]

display.encoding : str/unicode
    Defaults to the detected encoding of the console.
    Specifies the encoding to be used for strings returned by to_string,
    these are generally strings meant to be displayed on the console.
    [default: UTF-8] [currently: UTF-8]

display.expand_frame_repr : boolean
    Whether to print out the full DataFrame repr for wide DataFrames across
    multiple lines, `max_columns` is still respected, but the output will
    wrap-around across multiple "pages" if its width exceeds `display.width`.
    [default: True] [currently: True]

display.float_format : callable
    The callable should accept a floating point number and return
    a string with the desired format of the number. This is used
    in some places like SeriesFormatter.
    See formats.format.EngFormatter for an example.
    [default: None] [currently: None]

display.height : int
    Deprecated.
    [default: 60] [currently: 60]
    (Deprecated, use `display.max_rows` instead.)

display.large_repr : 'truncate'/'info'
    For DataFrames exceeding max_rows/max_cols, the repr (and HTML repr) can
    show a truncated table (the default from 0.13), or switch to the view from
    df.info() (the behaviour in earlier versions of pandas).
    [default: truncate] [currently: truncate]

display.latex.escape : bool
    This specifies if the to_latex method of a Dataframe uses escapes special
    characters.
    method. Valid values: False,True
    [default: True] [currently: True]

display.latex.longtable :bool
    This specifies if the to_latex method of a Dataframe uses the longtable
    format.
    method. Valid values: False,True
    [default: False] [currently: False]

display.latex.repr : boolean
    Whether to produce a latex DataFrame representation for jupyter
    environments that support it.
    (default: False)
    [default: False] [currently: False]

display.line_width : int
    Deprecated.
    [default: 80] [currently: 80]
    (Deprecated, use `display.width` instead.)

display.max_categories : int
    This sets the maximum number of categories pandas should output when
    printing out a `Categorical` or a Series of dtype "category".
    [default: 8] [currently: 8]

display.max_columns : int
    If max_cols is exceeded, switch to truncate view. Depending on
    `large_repr`, objects are either centrally truncated or printed as
    a summary view. 'None' value means unlimited.

    In case python/IPython is running in a terminal and `large_repr`
    equals 'truncate' this can be set to 0 and pandas will auto-detect
    the width of the terminal and print a truncated object which fits
    the screen width. The IPython notebook, IPython qtconsole, or IDLE
    do not run in a terminal and hence it is not possible to do
    correct auto-detection.
    [default: 20] [currently: 20]

display.max_colwidth : int
    The maximum width in characters of a column in the repr of
    a pandas data structure. When the column overflows, a "..."
    placeholder is embedded in the output.
    [default: 50] [currently: 200]

display.max_info_columns : int
    max_info_columns is used in DataFrame.info method to decide if
    per column information will be printed.
    [default: 100] [currently: 100]

display.max_info_rows : int or None
    df.info() will usually show null-counts for each column.
    For large frames this can be quite slow. max_info_rows and max_info_cols
    limit this null check only to frames with smaller dimensions than
    specified.
    [default: 1690785] [currently: 1690785]

display.max_rows : int
    If max_rows is exceeded, switch to truncate view. Depending on
    `large_repr`, objects are either centrally truncated or printed as
    a summary view. 'None' value means unlimited.

    In case python/IPython is running in a terminal and `large_repr`
    equals 'truncate' this can be set to 0 and pandas will auto-detect
    the height of the terminal and print a truncated object which fits
    the screen height. The IPython notebook, IPython qtconsole, or
    IDLE do not run in a terminal and hence it is not possible to do
    correct auto-detection.
    [default: 60] [currently: 60]

display.max_seq_items : int or None
    when pretty-printing a long sequence, no more then `max_seq_items`
    will be printed. If items are omitted, they will be denoted by the
    addition of "..." to the resulting string.

    If set to None, the number of items to be printed is unlimited.
    [default: 100] [currently: 100]

display.memory_usage : bool, string or None
    This specifies if the memory usage of a DataFrame should be displayed when
    df.info() is called. Valid values True,False,'deep'
    [default: True] [currently: True]

display.mpl_style : bool
    Setting this to 'default' will modify the rcParams used by matplotlib
    to give plots a more pleasing visual style by default.
    Setting this to None/False restores the values to their initial value.
    [default: None] [currently: None]

display.multi_sparse : boolean
    "sparsify" MultiIndex display (don't display repeated
    elements in outer levels within groups)
    [default: True] [currently: True]

display.notebook_repr_html : boolean
    When True, IPython notebook will use html representation for
    pandas objects (if it is available).
    [default: True] [currently: True]

display.pprint_nest_depth : int
    Controls the number of nested levels to process when pretty-printing
    [default: 3] [currently: 3]

display.precision : int
    Floating point output precision (number of significant digits). This is
    only a suggestion
    [default: 6] [currently: 6]

display.show_dimensions : boolean or 'truncate'
    Whether to print out dimensions at the end of DataFrame repr.
    If 'truncate' is specified, only print out the dimensions if the
    frame is truncated (e.g. not display all rows and/or columns)
    [default: truncate] [currently: truncate]

display.unicode.ambiguous_as_wide : boolean
    Whether to use the Unicode East Asian Width to calculate the display text
    width.
    Enabling this may affect to the performance (default: False)
    [default: False] [currently: False]

display.unicode.east_asian_width : boolean
    Whether to use the Unicode East Asian Width to calculate the display text
    width.
    Enabling this may affect to the performance (default: False)
    [default: False] [currently: False]

display.width : int
    Width of the display in characters. In case python/IPython is running in
    a terminal this can be set to None and pandas will correctly auto-detect
    the width.
    Note that the IPython notebook, IPython qtconsole, or IDLE do not run in a
    terminal and hence it is not possible to correctly detect the width.
    [default: 80] [currently: 80]

io.excel.xls.writer : string
    The default Excel writer engine for 'xls' files. Available options:
    'xlwt' (the default).
    [default: xlwt] [currently: xlwt]

io.excel.xlsm.writer : string
    The default Excel writer engine for 'xlsm' files. Available options:
    'openpyxl' (the default).
    [default: openpyxl] [currently: openpyxl]

io.excel.xlsx.writer : string
    The default Excel writer engine for 'xlsx' files. Available options:
    'xlsxwriter' (the default), 'openpyxl'.
    [default: xlsxwriter] [currently: xlsxwriter]

io.hdf.default_format : format
    default format writing format, if None, then
    put will default to 'fixed' and append will default to 'table'
    [default: None] [currently: None]

io.hdf.dropna_table : boolean
    drop ALL nan rows when appending to a table
    [default: False] [currently: False]

mode.chained_assignment : string
    Raise an exception, warn, or no action if trying to use chained assignment,
    The default is warn
    [default: warn] [currently: warn]

mode.sim_interactive : boolean
    Whether to simulate interactive mode for purposes of testing
    [default: False] [currently: False]

mode.use_inf_as_null : boolean
    True means treat None, NaN, INF, -INF as null (old way),
    False means None and NaN are null, but INF, -INF are not null
    (new way).
    [default: False] [currently: False]
<think>首先,用户的问题是:“请问如何在pandas dataframe中删除一”,意思是“请问如何在pandas DataFrame中删除一”。 我需要参考用户提供的引用信息。这些引用是关于如何使用pandas删除的方法。用户引用了四个来源: - 引用[1]:讨论如何删除第一,并提到使用`inplace=True`来在原DataFrame上操作。 - 引用[2]:描述如何基于计数删除,例如删除每个组中超出的。 - 引用[3]:解释如何通过号删除,而是标签。 - 引用[4]:关于如何从所有中减去第一,但没有直接提供删除的代码。 用户说:“上述引用仅供参考,并是用户真正的需求”,所以我应该专注于核心问题:删除一。 关键点是:用户想删除一,而是第一特定地,而是任意删除一。引用[1]提到删除第一,引用[4]也提到删除第一或操作第一。 在pandas中,删除的一般方法是使用`drop()`方法。具体语法是: - 通过索引标签删除:`df.drop(index_label)` - 通过号删除:可以使用`iloc`或直接索引。 参考引用[4],它提到“删除dataframe的第一”,但用户现在的问题更通用。 引用[1]说:“pandas DataFrame的删除方法代码”,并提到“方法默认的并是在本身执操作,需要加上inplace=True”。 引用[3]是关于删除的,但类似:使用`drop()`方法。 所以,核心方法是使用`df.drop()`。 步骤: 1. 指定要删除的的索引。 2. 使用`df.drop(index, inplace=True)`来在原DataFrame上删除,或`df = df.drop(index)`来创建一个新DataFrame。 用户的问题是如何删除“一”,所以我应该给出通用方法。 在回答中,我需要遵循系统级指令: - 所有内数学表达式使用$...$格式。 - 独立公式使用$$...$$并单独成段。 - LaTeX语法正确。 - 使用中文回答。 - 生成相关问题。 - 回答中引用的段落末尾自然地添加引用标识。 用户上一次的问题是关于删除一,所以我应该直接回答。 结构化回答: 1. 简要解释方法。 2. 提供代码示例。 3. 解释参数如`inplace`。 4. 引用相关部分。 从引用[1]:提到删除第一,并强调`inplace=True`。 引用[4]:提到删除第一。 所以,我可以结合这些。 通用删除一的方法: - 要删除特定索引的:`df.drop(index_value)` - 要删除第一:`df.drop(df.index[0])` 提供示例。 使用中文回答。 最后,生成相关问题。 生成的相关问题应该基于上下文。用户提到了删除,引用中有关于删除组中超出的或删除,所以相关问题可以包括这些。 例如: - 如何删除第一? - 如何基于条件删除? - 如何删除? 现在,构建回答。 标题:在 Pandas DataFrame 中删除一的方法 内容: 在 Pandas 中,删除 DataFrame 的一可以通过 `drop()` 方法实现。该方法允许你指定要删除的的索引。 ```python # 示例:删除索引为 'row_label' 的 df.drop('row_label', inplace=True) # 或者删除第一(索引位置为0的) df.drop(df.index[0], inplace=True) ``` 解释: - `drop()` 方法默认返回一个新的 DataFrame会修改原始数据。如果要在原 DataFrame 上操作,需设置 `inplace=True`。 - 要删除,请设置 `axis=0` 或省略,因为默认是方向(axis=0)。删除时需设置 `axis=1`。 参考引用[1],其中提到使用 `inplace=True` 来在原 DataFrame 上操作[^1]。 如果你知道号而是索引标签,可以使用 `iloc`: ```python # 删除第一号为0) df = df.drop(df.index[0]) ``` 引用[4]也讨论了删除第一的场景[^4]。 §§相关问题§§ 1. 如何删除 Pandas DataFrame 的第一? 2. 如何基于条件删除? 3. 如何删除 Pandas DataFrame 中的? 确保语言是中文。 </think>### 在 Pandas DataFrame 中删除一的方法 在 Pandas 中,删除 DataFrame 的一主要通过 `drop()` 方法实现。该方法允许你指定要删除的索引(索引标签或位置),并返回一个新的 DataFrame 或修改原始 DataFrame。关键点: - **默认为**:`drop()` 会修改原始 DataFrame,而是返回一个新对象。如果要在原数据上直接操作,需设置参数 `inplace=True`。 - **索引指定**:可以通过索引标签(如字符串或数字)或位置(整数)来指定要删除的。 - **axis 参数**:删除时,默认 `axis=0`(方向),通常可以省略。 下面以一个示例 DataFrame 说明操作步骤: ```python import pandas as pd # 创建示例 DataFrame data = {'A': [1, 2, 3], 'B': [4, 5, 6]} df = pd.DataFrame(data, index=['row1', 'row2', 'row3']) print("原始 DataFrame:") print(df) ``` 输出: ``` 原始 DataFrame: A B row1 1 4 row2 2 5 row3 3 6 ``` #### 方法 1: 通过索引标签删除指定 如果你知道的索引标签(例如要删除 'row2'),使用 `drop()` 传入索引标签: ```python # 删除索引为 'row2' 的,并返回新 DataFrame(原 DataFrame 变) new_df = df.drop('row2') print("删除后返回的新 DataFrame:") print(new_df) # 或者直接修改原 DataFrame:设置 inplace=True df.drop('row2', inplace=True) print("原 DataFrame 修改后:") print(df) ``` 输出: ``` 删除后返回的新 DataFrame: A B row1 1 4 row3 3 6 原 DataFrame 修改后: A B row1 1 4 row3 3 6 ``` #### 方法 2: 通过位置删除指定(例如删除第一) 如果知道索引标签但知道位置(例如删除第一),使用 `df.index` 或 `iloc` 获取索引: ```python # 删除第一(位置为 0 的) df.drop(df.index[0], inplace=True) # 使用 df.index 获取索引标签 print("删除第一后:") print(df) # 另一种方式:直接通过位置索引(推荐用于未知标签时) df = df.iloc[1:] # 保留从第二开始的所有,等效于删除第一 ``` 引用[1]和[4]都讨论了删除第一的场景,并强调使用 `inplace=True` 来直接修改原始数据[^1][^4]。 #### 关键参数说明 - `inplace=True`: 在原 DataFrame 上操作,避免赋值操作(如 `df = df.drop(...)`)。 - 错误处理:如果要删除的索引存在,会抛出 `KeyError`。可以用 `errors='ignore'` 忽略错误,例如 `df.drop('rowx', errors='ignore', inplace=True)`。 - 性能:删除操作的时间复杂度为 $O(n)$,其中 $n$ 是数。对于大数据集,推荐使用 `inplace=True` 减少内存开销。 #### 常见错误和注意事项 - **未使用 `inplace=True`**:操作后忘记赋值或设置 `inplace` 会导致原始数据未更改(引用[1]强调了这一点[^1])。 - **条件删除**:如果需基于条件删除(如删除值大于 5 的),结合布尔索引更高效: ```python df = df[df['A'] <= 5] # 保留 'A' 值 <=5 的,等效于删除条件 ``` - **组内删除**:引用[2]提到基于分组删除多余(如每组只保留前 3 ),可用 `groupby` 实现[^2]。
评论 26
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值