Python 如何检索数据框中的列数?
如何以编程方式检索数据帧中的列数?我希望有这样的事情:Python 如何检索数据框中的列数?,python,pandas,dataframe,Python,Pandas,Dataframe,如何以编程方式检索数据帧中的列数?我希望有这样的事情: df.num_columns 像这样: import pandas as pd df = pd.DataFrame({"pear": [1,2,3], "apple": [2,3,4], "orange": [3,4,5]}) len(df.columns) 3 备选方案: df.shape[1] (df.shape[0]是行数)如果保存数据帧的变量称为df,则: len(df.columns) 给出列数 #use a regul
df.num_columns
像这样:
import pandas as pd
df = pd.DataFrame({"pear": [1,2,3], "apple": [2,3,4], "orange": [3,4,5]})
len(df.columns)
3
备选方案:
df.shape[1]
(
df.shape[0]
是行数)如果保存数据帧的变量称为df,则:
len(df.columns)
给出列数
#use a regular expression to parse the column count
#https://docs.python.org/3/library/re.html
buffer = io.StringIO()
df.info(buf=buffer)
s = buffer.getvalue()
pat=re.search(r"total\s{1}[0-9]\s{1}column",s)
print(s)
phrase=pat.group(0)
value=re.findall(r'[0-9]+',phrase)[0]
print(int(value))
对于需要行数的用户:
len(df.index)
对于同时包含行数和列数的元组:
df.shape
这对我来说很有效(list(df))。df.info()函数将给出如下结果。
如果您使用的是不带sep参数或带“,”的sep的熊猫读取csv方法
raw\u data=pd.read\u csv(“a1:\aa2/aaa3/data.csv”)
原始数据。信息()
范围索引:5144个条目,0到5143
栏目:145个条目,从R_fighter到R_age
有多个选项可以获取列号和列信息,例如:让我们检查一下 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)
打印(li_count)很惊讶我还没有看到这一点,因此,无需进一步讨论,这里是:
为了在总形状中包含行索引“列”的数量,我个人会将列数
df.columns.size
与属性pd.index.nlevels
/pd.MultiIndex.nlevels
相加:
设置虚拟数据
import pandas as pd
flat_index = pd.Index([0, 1, 2])
multi_index = pd.MultiIndex.from_tuples([("a", 1), ("a", 2), ("b", 1), names=["letter", "id"])
columns = ["cat", "dog", "fish"]
data = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flat_df = pd.DataFrame(data, index=flat_index, columns=columns)
multi_df = pd.DataFrame(data, index=multi_index, columns=columns)
# Show data
# -----------------
# 3 columns, 4 including the index
print(flat_df)
cat dog fish
id
0 1 2 3
1 4 5 6
2 7 8 9
# -----------------
# 3 columns, 5 including the index
print(multi_df)
cat dog fish
letter id
a 1 1 2 3
2 4 5 6
b 1 7 8 9
将流程编写为函数:
def total_ncols(df, include_index=False):
ncols = df.columns.size
if include_index is True:
ncols += df.index.nlevels
return ncols
print("Ignore the index:")
print(total_ncols(flat_df), total_ncols(multi_df))
print("Include the index:")
print(total_ncols(flat_df, include_index=True), total_ncols(multi_df, include_index=True))
这张照片是:
Ignore the index:
3 3
Include the index:
4 5
如果只想在索引为pd.MultiIndex
时包含索引数,则可以在定义的函数中插入isinstance
检查
作为替代,您可以使用df.reset_index().columns.size
来实现相同的结果,但这不会有那么好的效果,因为我们将临时向索引中插入新列,并在获取列数之前创建新索引
#use a regular expression to parse the column count
#https://docs.python.org/3/library/re.html
buffer = io.StringIO()
df.info(buf=buffer)
s = buffer.getvalue()
pat=re.search(r"total\s{1}[0-9]\s{1}column",s)
print(s)
phrase=pat.group(0)
value=re.findall(r'[0-9]+',phrase)[0]
print(int(value))
给出行的长度
3
[Program finished]
这是:
pandas
- excel引擎:
xlsxwriter
- excel引擎:
->len(df.columns)
28
->df.shape[1]
28
- 这里:
df.shape=(592,28)
- 相关的
- 行数:
->df.shape[0]
592
- 行数:
- 这里:
->df.columns.shape[0]
28
- 这里:
df.columns.shape=(28,)
- 这里:
->df.columns.size
28
df.shape
给出了一个元组,其中包含(n_行,n_列)@mkln如果你将df.shape[1]作为答案,我会+1。这是与numpy合作的更好方式,值得单独回答。完成@PhilCooper也许你可以解释为什么df.shape
更好?我的猜测是,它不调用函数,而只是从内存?+1中读取属性,因为我喜欢鼓励使用martix类型语法对numpy和pandas对象进行寻址。(df.形状vs.长度(df.柱))。说实话,如果您查看形状的pandas描述符,它调用len(df.columns),但numpy数组和矩阵将它们作为属性。最有效的向量化操作可以使用常规python语法来完成,而不是向量化操作,并且几乎总是错误的(numba/jit操作除外),不会len(df)
给你行吗?@padraiccnningham pandas有太多容易忘记的快捷方式,所以我宁愿忽略它们,而是使用主逻辑来解决问题。有时您可能会牺牲处理速度,但我认为我的编码时间和代码可读性比几秒钟的处理时间更重要。在这种情况下:如果你知道行的数量可以用len(df.index)计算,那么下次你需要列的数量时,很自然地要用len(df.columns)来计算。请编辑您的答案并加以改进,或者将其作为评论发布。不要这样做。它创建了一个新的列表,浪费了内存和速度。我正在寻找一个解决方案,该解决方案还考虑了groupby操作后转换为(多)索引的列。我算出了len(df.axes[0].names)+df.shape[1]
,但它看起来远远不是最优的。有什么想法吗?现在没有一个现有的答案能解决这个问题。@jangorecki,但这与这个问题毫无关系。如果事物在数据帧的索引中,则它们不被视为列。虽然这似乎是一种任意的区别,但pandas对索引值和列序列的处理在某些操作中非常不同。无论如何,当您使用groupby时,您可以使用as_index=False
阻止创建MultiIndex
。@ALollz它们不被视为列的事实只是一个细节,来自SQL、R和其他技术的工程师希望将列分组为列,而不是属性。@jangorecki一个简单的方法是len(df.reset_index().columns)
as reset_index会将所有索引转换为列。但@Aloltz指出,这确实是一个截然不同的问题。我建议
3
[Program finished]