kiitosu
kiitosu

Reputation: 117

What happen when I use double bracket with DataFrame?

When I do this

test = pd.DataFrame([[1, 2, 3], [4, 5, 6]])
print(type(test))
print(test)
print('\n')
print(type(test[1]))
print(test[1])
print('\n')
print(type(test[[1]]))
print(test[[1]])

I get this.

<class 'pandas.core.frame.DataFrame'>
   0  1  2
0  1  2  3
1  4  5  6


<class 'pandas.core.series.Series'>
0    2
1    5
Name: 1, dtype: int64


<class 'pandas.core.frame.DataFrame'>
   1
0  2
1  5

I think it's natural I get series when I specify one of DataFrame column's key.

But I don't understand why I get DataFrame when I specify one of DataFrame column's key in double brackets.

What's haappening?

Upvotes: 0

Views: 259

Answers (1)

Muhammad Hassan
Muhammad Hassan

Reputation: 4229

You are not specifying row key when you do test[1] but actually you are accessing dataframe's column 1. Check your column names, and they are 0, 1, 2. Now when you try to access this df[[1]] you are passing a list of columns i.e. [1] and that's why it returns you a dataframe.

Plz read this as well: What is the difference between a pandas Series and a single-column DataFrame?

Upvotes: 1

Related Questions