Pandas DataFrame中print(list(df.columns.values))输出[0,1,2]的含义是什么?
Hey there! Let's clear up this confusion for you step by step.
When you create a DataFrame using df = pd.DataFrame(np.array([[1, 2, 3], [4, 5, 6]])) without explicitly defining column names, Pandas automatically assigns default integer column labels starting from 0.
The output [0, 1, 2] you're seeing is exactly these default column identifiers:
0refers to the first column of your DataFrame (containing values1and4)1refers to the second column (containing values2and5)2refers to the third column (containing values3and6)
Your earlier misunderstanding about 2 representing the number of rows is a common mix-up, but that's not the case here. The number of default column labels matches the number of columns in your DataFrame (you have 3 columns, so labels go from 0 to 2). The number of rows (2 in your example) has no impact on these column labels.
To make this more concrete, if you explicitly set column names when creating the DataFrame, like this:
import pandas as pd import numpy as np df = pd.DataFrame(np.array([[1, 2, 3], [4, 5, 6]]), columns=['Col1', 'Col2', 'Col3']) print(list(df.columns.values))
You'd get the output ['Col1', 'Col2', 'Col3'] instead of the integer labels. This shows that the default integers are just a fallback when no column names are provided.
内容的提问来源于stack exchange,提问作者Ayush Goyal

