English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Pandas IO Operation Example
The two main functions for reading text files are read_csv() and read_table(). They both use the same parsing code to intelligently convert table data into DataFrame objects:
pandas.read_csv(filepath_or_buffer, sep=',', delimiter=None, header='infer', names=None, index_col=None, usecols=None
pandas.read_csv(filepath_or_buffer, sep='\t', delimiter=None, header='infer', names=None, index_col=None, usecols=None
Save this data as temp.csv and perform operations on it.
S.No,Name,Age,City,Salary 1,Tom,28,Toronto,20000 2,Lee,32,HongKong,3000 3,Steven,43,Bay Area,8300 4,Ram,38,Hyderabad,3900
read.csv reads data from a csv file and creates a DataFrame object.
import pandas as pd df=pd.read_csv("temp.csv") print df
النتيجة التشغيلية كالتالي:
S.No Name Age City Salary 0 1 Tom 28 Toronto 20000 1 2 Lee 32 HongKong 3000 2 3 Steven 43 Bay Area 8300 3 4 Ram 38 Hyderabad 3900
This will specify a column in the csv file to use index_col for custom indexing.
import pandas as pd df=pd.read_csv("temp.csv",index_col=['S.No']) print df
النتيجة التشغيلية كالتالي:
S.No Name Age City Salary 1 Tom 28 Toronto 20000 2 Lee 32 HongKong 3000 3 Steven 43 Bay Area 8300 4 Ram 38 Hyderabad 3900
يمكن أن تكون dtype كمعامل دالة.
import pandas as pd df = pd.read_csv("temp.csv", dtype={'Salary': np.float64}) print df.dtypes
النتيجة التشغيلية كالتالي:
S.No int64 Name object Age int64 City object Salary float64 dtype: object
بالتشخيص، dtype لسطر Salary هو int، ولكن يتم عرضه كfloat لأننا قمنا بتحويل النوع بشكل واضح. لذلك، تبدو البيانات مثل float.
إذن، يبدو البيانات مثل float −
S.No Name Age City Salary 0 1 Tom 28 Toronto 20000.0 1 2 Lee 32 HongKong 3000.0 2 3 Steven 43 Bay Area 8300.0 3 4 Ram 38 Hyderabad 3900.0
استخدم المعامل names لتعيين أسماء العناوين.
import pandas as pd df=pd.read_csv("temp.csv", names=['a', 'b', 'c','d','e']) print df
النتيجة التشغيلية كالتالي:
a b c d e 0 S.No Name Age City Salary 1 1 Tom 28 Toronto 20000 2 2 Lee 32 HongKong 3000 3 3 Steven 43 Bay Area 8300 4 4 Ram 38 Hyderabad 3900
لاحظ أن اسم الرأس تم إضافة اسم مخصص إليه، ولكن لم يتم إزالة الرأس من الملف بعد. الآن، نستخدم المعامل header لإزالته.
إذا لم يكن العنوان في السطر الأول، فإنه يتم نقل رقم السطر إلى العنوان. سيقوم هذا بإغلاق السطور السابقة.
import pandas as pd df=pd.read_csv("temp.csv",names=['a','b','c','d','e'],header=0) print df
النتيجة التشغيلية كالتالي:
a b c d e 0 S.No Name Age City Salary 1 1 Tom 28 Toronto 20000 2 2 Lee 32 HongKong 3000 3 3 Steven 43 Bay Area 8300 4 4 Ram 38 Hyderabad 3900
skiprows لتخطي عدد معين من الصفوف.
import pandas as pd df=pd.read_csv("temp.csv", skiprows=2) print df
النتيجة التشغيلية كالتالي:
2 Lee 32 HongKong 3000 0 3 Steven 43 Bay Area 8300 1 4 Ram 38 Hyderabad 3900