English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Pandas DataFrame

   Basic operations of Pandas DataFrame

DataFrame is a two-dimensional data structure, that is, data is aligned in rows and columns in table form.

DataFrame functions

Potential columns are of different types Variable size Labeled axis (rows and columns) Arithmetic operations can be performed on rows and columns

Structure

pandas.Series

The structure of Series is as follows:

Let's assume we are creating a DataFrame with student data.

We can consider it as a SQL table or an electronic spreadsheet data representation.

pandas.DataFrame

The following constructors can be used to create a pandas DataFrame-

 pandas.DataFrame(data, index, columns, dtype, copy)

Parameter description:

data: Data can take various forms, such as ndarray, series, mapping, list, dict, constants, and another DataFrame. index: For row labels, if no index is passed, the index used for the result frame is Optional Default np.arange(n). columns: Für die Spaltenbezeichner, die optionale Standardnotation ist-np.arange(n)。Nur wenn kein Index übergeben wird,so ist es. dtype: Datenart jeder Spalte. copy: Wenn der Standardwert False ist, wird dieses Kommando (oder jedes seiner Kommandos) zum Kopieren der Daten verwendet.

Erstellen eines DataFrame

Man kann mit verschiedenen Eingaben pandas DataFrame erstellen-

Listen dict Series Numpy ndarrays Ein weiterer DataFrame

In den folgenden Abschnitten dieses Kapitels werden wir sehen, wie man diese Eingaben verwendet, um einen DataFrame zu erstellen.

Erstellen eines leeren DataFrame

Man kann einen grundlegenden DataFrame als leeren Dataframe erstellen.

 # Dateiname: pandas.py
 # author by: de.oldtoolbag.com 
 # Importiere das Abhängigkeitspaket pandas und benenne es als Alias
 import pandas as pd
 df = pd.DataFrame()
 print(df)

Laufender Output:

 Leere DataFrame
 Spalten: []
 Index: []

Von Listen erstellen DataFrame

 # Dateiname: pandas.py
 # author by: de.oldtoolbag.com 
 # Importiere das Abhängigkeitspaket pandas und benenne es als Alias
 import pandas as pd
 data = [1,2,3,4,5}
 df = pd.DataFrame(data)
 print(df)

Laufender Output:

 0
 0 1
 1 2
 2 3
 3 4
 4 5
 # Dateiname: pandas.py
 # author by: de.oldtoolbag.com 
 # Importiere das Abhängigkeitspaket pandas und benenne es als Alias
 import pandas as pd
 data = [['Alex',10],['Bob',12],['Clarke',13}]
 df = pd.DataFrame(data, columns=['Name', 'Alter'])
 print(df)

Laufender Output:

       Name     Alter
 0     Alex     10
 1     Bob      12
 2     Clarke   13
 # Dateiname: pandas.py
 # author by: de.oldtoolbag.com 
 # Importiere das Abhängigkeitspaket pandas und benenne es als Alias
 import pandas as pd
 data = [['Alex',10],['Bob',12],['Clarke',13}]
 df = pd.DataFrame(data, columns=['Name', 'Alter'], dtype=float)
 print df

Laufender Output:

 
      Name   Alter
 0    Alex   10.0
 1    Bob    12.0
 2    Clarke 13.0
注意:Der dtype-Parameter ändert den Typ der 'Alter'-Spalte in Fließkomma.

von ndarray / List-Dictionary erstellt eine DataFrame

Die Länge aller ndarray muss gleich sein. Wenn index übergeben wird, sollte die Länge des Index gleich der Länge des Arrays sein。
Wenn keine Index übergeben wird, ist der Standardindex range(n),wobei n die Länge des Arrays ist。

 # Dateiname: pandas.py
 # author by: de.oldtoolbag.com 
 # Importiere das Abhängigkeitspaket pandas und benenne es als Alias
 import pandas as pd
 data = {'Name':['Tom', 'Jack', 'Steve', 'Ricky'], 'Age':28,34,29,42}]
 df = pd.DataFrame(data)
 print(df)

Laufender Output:

 
    Alter Name
 0   28   Tom
 1   34   Jack
 2   29   Steve
 3   42   Ricky
注意:Einhaltung des Wertes 0、1、2、3。它们是使用功能范围(n)分配给每个对象的默认索引。

Wir verwenden Arrays, um eine DataFrame mit Index zu erstellen.

 # Dateiname: pandas.py
 # author by: de.oldtoolbag.com 
 # Importiere das Abhängigkeitspaket pandas und benenne es als Alias
 import pandas as pd
 data = {'Name':['Tom', 'Jack', 'Steve', 'Ricky'], 'Age':28,34,29,42}]
 df = pd.DataFrame(data, index=['Rang1','Rang2','Rang3','Rang4'])
 print(df)

Laufender Output:

 
       Alter Name
 rank1 28 Tom
 rank2 34 Jack
 rank3 29 Steve
 rank4 42 Ricky
注意:index参数为每行分配一个索引。

从字典列表创建DataFrame

字典列表可以作为输入数据传递以创建DataFrame。默认情况下,字典键被用作列名。
下面的示例演示如何通过传递字典列表来创建DataFrame。

 # Dateiname: pandas.py
 # author by: de.oldtoolbag.com 
 # Importiere das Abhängigkeitspaket pandas und benenne es als Alias
 import pandas as pd
 data = [{'a': 1, 'b': 2},{'a': 5, 'b': 10, 'c': 20}]
 df = pd.DataFrame(data)
 print(df)

Laufender Output:

     a b c
 0 1 2 NaN
 1 5 10 20.0
注意:NaN(非数字)会附加在缺失区域中。

下面的示例演示如何通过传递字典列表和行索引来创建DataFrame。

 # Dateiname: pandas.py
 # author by: de.oldtoolbag.com 
 # Importiere das Abhängigkeitspaket pandas und benenne es als Alias
 import pandas as pd
 data = [{'a': 1, 'b': 2},{'a': 5, 'b': 10, 'c': 20}]
 df = pd.DataFrame(data, index=['first', 'second'])
 print(df)

Laufender Output:

          a b c
 first 1 2 NaN
 second 5 10 20.0

下面的示例演示如何创建包含字典,行索引和列索引的列表的DataFrame。

 # Dateiname: pandas.py
 # author by: de.oldtoolbag.com 
 # Importiere das Abhängigkeitspaket pandas und benenne es als Alias
 import pandas as pd
 data = [{'a': 1, 'b': 2},{'a': 5, 'b': 10, 'c': 20}]
 # 有两个列索引,值与字典键相同
 df1 = pd.DataFrame(data, index=['first', 'second'], columns=['a', 'b'])
 # 有两个列索引
 df2 = pd.DataFrame(data, index=['first', 'second'], columns=['a', 'b', "c":1'])
 print(df1)
 print(df2)

Laufender Output:

 #df1 output
       a b
 first 1 2
 second 5 10
 #df2 output
       a b1
 first 1 NaN
 second 5 NaN
注意:df2 DataFrame是使用除字典键以外的列索引创建的;因此,将NaN附加到位。而df1是使用与字典键相同的列索引创建的,因此附加了NaN。

从Dict Series创建DataFrame

可以传递系列字典以形成DataFrame。结果索引是所有通过的系列索引的并集。

 # Dateiname: pandas.py
 # author by: de.oldtoolbag.com 
 # Importiere das Abhängigkeitspaket pandas und benenne es als Alias
 import pandas as pd
 d = {'one' : pd.Series([1, 2, 3], index=['a', 'b', 'c']),
    'two' : pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])}
 df = pd.DataFrame(d
 print(df)

Laufender Output:

   one two
 a 1.0 1
 b 2.0 2
 c 3.0 3
 d NaN 4

对于第一个系列,没有传递标签'd',但是结果是,对于d标签,附加了NaN。
现在让我们通过示例了解列的选择,添加和删除。

列查询

我们将从DataFrame中选择一列来了解这一点。

 # Dateiname: pandas.py
 # author by: de.oldtoolbag.com 
 # Importiere das Abhängigkeitspaket pandas und benenne es als Alias
 
 import pandas as pd
 d = {'one' : pd.Series([1, 2, 3], index=['a', 'b', 'c']),
    'two' : pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])}
 df = pd.DataFrame(d
 print(df ['one'])

Laufender Output:

   a 1.0
 b 2.0
 c 3.0
 d NaN
 Name: one, dtype: float64

列添加

我们将通过在现有数据框中添加新列来了解这一点。

# Dateiname: pandas.py
 # author by: de.oldtoolbag.com 
 # Importiere das Abhängigkeitspaket pandas und benenne es als Alias
 import pandas as pd
 d = {'one' : pd.Series([1, 2, 3], index=['a', 'b', 'c']),
    'two' : pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])}
 df = pd.DataFrame(d
 #通过传递新序列,向具有列标签的现有 DataFrame 对象添加新列
 print ("通过作为 Series 传递添加新列:")
 df['three']=pd.Series([10,20,30],index=['a','b','c'])
 print df
 print ("使用 DataFrame 中的现有列添加新列:")
 df['four']=df['one']+df['three']
 print(df)

Laufender Output:

 通过作为 Series 传递添加新列:
 one two three
 a 1.0 1 10.0
 b 2.0 2 20.0
 c 3.0 3 30.0
 d NaN 4 NaN
 使用 DataFrame 中的现有列添加新列:
 one two three four
 a 1.0 1 10.0 11.0
 b 2.0 2 20.0 22.0
 c 3.0 3 30.0 33.0
 d NaN 4 NaN NaN

列删除

可以删除或弹出列;让我们以一个实例来了解如何。

 # Dateiname: pandas.py
 # author by: de.oldtoolbag.com 
 # Importiere das Abhängigkeitspaket pandas und benenne es als Alias
 import pandas as pd
 d = {'one' : pd.Series([1, 2, 3], index=['a', 'b', 'c']), 
    'two' : pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd']), 
    'three' : pd.Series([10,20,30], index=['a','b','c'])}
 df = pd.DataFrame(d
 print ("Our dataframe is:")
 print(df)
 # using del function
 print ("Deleting the first column using del function:")
 del df['one']
 print(df)
 # using pop function
 print ("Deleting another column using POP function:")
 df.pop('two')
 print(df)

Laufender Output:

 Our dataframe is:
 one three two
 a 1.0 10.0 1
 b 2.0 20.0 2
 c 3.0 30.0 3
 d NaN NaN 4
 Deleting the first column using del function:
   three two
 a 10.0 1
 b 20.0 2
 c 30.0 3
 d NaN 4
 Deleting another column using POP function:
   three
 a 10.0
 b 20.0
 c 30.0
 d NaN

行查询、添加和删除

现在,我们将通过示例了解行的选择,添加和删除。让我们从选择的概念开始。

按标签查询

可以通过将行标签传递给loc函数来选择行。

 # Dateiname: pandas.py
 # author by: de.oldtoolbag.com 
 # Importiere das Abhängigkeitspaket pandas und benenne es als Alias
 import pandas as pd
 d = {'one' : pd.Series([1, 2, 3], index=['a', 'b', 'c']), 
    'two' : pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])}
 df = pd.DataFrame(d
 print(df.loc['b'])

Laufender Output:

 
   one 2.0
 two 2.0
 Name: b, dtype: float64

结果是一系列带有标签作为DataFrame列名称的系列。并且,系列的名称是用来检索它的标签。

通过整数位置查询

结可以通过将整数位置传递给iloc函数来选择行。

 # Dateiname: pandas.py
 # author by: de.oldtoolbag.com 
 # Importiere das Abhängigkeitspaket pandas und benenne es als Alias
 import pandas as pd
 d = {'one' : pd.Series([1, 2, 3], index=['a', 'b', 'c']),
    'two' : pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])}
 df = pd.DataFrame(d
 print(df.iloc[2])

Laufender Output:

 
   one 3.0
 two 3.0
 Name: c, dtype: float64

切片行

可以使用':'运算符选择多行。

 # Dateiname: pandas.py
 # author by: de.oldtoolbag.com 
 # Importiere das Abhängigkeitspaket pandas und benenne es als Alias
 import pandas as pd
 d = {'one' : pd.Series([1, 2, 3], index=['a', 'b', 'c']), 
    'two' : pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])}
 df = pd.DataFrame(d
 print(df[2:4])

Laufender Output:

 
     one two
 c 3.0 3
 d NaN 4

Zeilen hinzufügen

Fügen Sie neue Zeilen zur DataFrame hinzufügen, indem Sie die append-Funktion verwenden. Diese Funktion fügt Zeilen am Ende hinzu.

 # Dateiname: pandas.py
 # author by: de.oldtoolbag.com 
 # Importiere das Abhängigkeitspaket pandas und benenne es als Alias
 import pandas as pd
 df = pd.DataFrame([1, 2], [3, 4], columns = ['a','b'])
 df2 = pd.DataFrame([5, 6], [7, 8], columns = ['a','b'])
 df = df.append(df2)
 print(df)

Laufender Output:

 
     a b
 0 1 2
 1 3 4
 0 5 6
 1 7 8

Zeilen löschen

Zeilen aus dem DataFrame löschen, indem Sie die Index-Tags verwenden. Wenn die Tags dupliziert sind, werden mehrere Zeilen gelöscht.
Wenn Sie beobachten, dass in dem obigen Beispiel die Tags dupliziert sind. Lassen Sie uns einen Tag löschen und sehen, wie viele Zeilen gelöscht werden.

 # Dateiname: pandas.py
 # author by: de.oldtoolbag.com 
 # Importiere das Abhängigkeitspaket pandas und benenne es als Alias
 import pandas as pd
 df = pd.DataFrame([1, 2], [3, 4], columns = ['a','b'])
 df2 = pd.DataFrame([5, 6], [7, 8], columns = ['a','b'])
 df = df.append(df2)
 # Entferne Zeilen mit dem Label 0
 df = df.drop(0)
 print(df)

Laufender Output:

 
     a b
 1 3 4
 1 7 8

In dem obigen Beispiel wurden zwei Zeilen entfernt, da diese zwei Zeilen den gleichen Tag 0 enthalten.