Get object size from read_csv in pandas

Viewed 5148

I read a csv file and find the size of this

import pandas as pd
data = pd.read_csv("train.csv")
data.size

I got 10692 in result But I try another way

y = data["Survived"]

This time, I only got 891 in length. As I think it must be 10692. Would you like finding out the difference? I downloaded data in here

https://www.kaggle.com/c/titanic/data?select=train.csv

3 Answers

It is expected, because DataFrame.size working different, it counts all values of DataFrame.

data = pd.DataFrame({
        'A':list('abcdef'),
         'B':[4,5,4,5,5,4],
         'Survived':[7,8,9,4,2,3],

})

print (data)
   A  B  Survived
0  a  4         7
1  b  5         8
2  c  4         9
3  d  5         4
4  e  5         2
5  f  4         3

#3 columns x 6 rows = 18
print (data.size)
18

y = data["Survived"]
print (y)
0    7
1    8
2    9
3    4
4    2
5    3
Name: Survived, dtype: int64

#nuber of values in Series/column
print (y.size)
6

If want number of rows and columns:

print (data.shape)
(6, 3)

Or number of rows:

print (len(data))
6

10692 is the total number of elements dataset contains.

It has 891 rows and 12 columns.

df = pd.read_csv("train.csv")
df.info()

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 891 entries, 0 to 890
Data columns (total 12 columns):
 #   Column       Non-Null Count  Dtype  
---  ------       --------------  -----  
 0   PassengerId  891 non-null    int64  
 1   Survived     891 non-null    int64  
 2   Pclass       891 non-null    int64
   .....

Moreover data.info() is an other way to get the shape information about your DataFrame. To get the exactly "size" in terms of memory usage just add the parameter memory_usage="deep".

Related