问题:如何检索Pandas数据框中的列数?

您如何以编程方式检索熊猫数据框中的列数?我希望有这样的东西:

df.num_columns

How do you programmatically retrieve the number of columns in a pandas dataframe? I was hoping for something like:

df.num_columns

回答 0

像这样:

import pandas as pd
df = pd.DataFrame({"pear": [1,2,3], "apple": [2,3,4], "orange": [3,4,5]})

len(df.columns)
3

Like so:

import pandas as pd
df = pd.DataFrame({"pear": [1,2,3], "apple": [2,3,4], "orange": [3,4,5]})

len(df.columns)
3

回答 1

选择:

df.shape[1]

df.shape[0]是行数)

Alternative:

df.shape[1]

(df.shape[0] is the number of rows)


回答 2

如果保存数据帧的变量称为df,则:

len(df.columns)

给出列数。

对于那些想要行数的人:

len(df.index)

对于包含行数和列数的元组:

df.shape

If the variable holding the dataframe is called df, then:

len(df.columns)

gives the number of columns.

And for those who want the number of rows:

len(df.index)

For a tuple containing the number of both rows and columns:

df.shape

回答 3

len(list(df))对我有用。

This worked for me len(list(df)).


回答 4

df.info()函数将为您提供如下结果。如果您使用的是不带sep参数或不带“,”的sep的Pandas的read_csv方法。

raw_data = pd.read_csv("a1:\aa2/aaa3/data.csv")
raw_data.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 5144 entries, 0 to 5143
Columns: 145 entries, R_fighter to R_age

df.info() function will give you result something like as below. If you are using read_csv method of Pandas without sep parameter or sep with “,”.

raw_data = pd.read_csv("a1:\aa2/aaa3/data.csv")
raw_data.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 5144 entries, 0 to 5143
Columns: 145 entries, R_fighter to R_age

回答 5

有多种选择来获取列号和列信息,例如:
让我们检查一下。

local_df = pd.DataFrame(np.random.randint(1,12,size =(2,6)),列= [‘a’,’b’,’c’,’d’,’e’,’f ‘])1. local_df.shape [1]-> Shape属性返回元组为(行和列)(0,1)。

  1. local_df.info()-> info方法将返回有关数据框及其列的详细信息,例如列数,列的数据类型,非空值计数,数据帧的内存使用情况

  2. len(local_df.columns)->列属性将返回数据框列的索引对象,而len函数将返回可用列总数。

  3. local_df.head(0)->具有参数0的head方法将返回df的第一行,实际上仅是标题。

假设列数不超过10。为了循环乐趣:local_df中x的li_count = 0:li_count = li_count +1 print(li_count)

There are multiple option to get column number and column information such as:
let’s check them.

local_df = pd.DataFrame(np.random.randint(1,12,size=(2,6)),columns =[‘a’,’b’,’c’,’d’,’e’,’f’]) 1. local_df.shape[1] –> Shape attribute return tuple as (row & columns) (0,1).

  1. local_df.info() –> info Method will return detailed information about data frame and it’s columns such column count, data type of columns, Not null value count, memory usage by Data Frame

  2. len(local_df.columns) –> columns attribute will return index object of data frame columns & len function will return total available columns.

  3. local_df.head(0) –> head method with parameter 0 will return 1st row of df which actually nothing but header.

Assuming number of columns are not more than 10. For loop fun: li_count =0 for x in local_df: li_count =li_count + 1 print(li_count)


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。