数据帧(DataFrame)是二维数据结构,即数据以行和列的表格方式排列。 可以视为 SQL 表或电子表格数据表示。
数据帧(DataFrame)的功能特点:
- 潜在的列是不同的类型
- 大小可变
- 标记轴(行和列)
- 可以对行和列执行算术运算
pandas.DataFrame( data, index, columns, dtype, copy)
构造函数的参数如下:
data
数据采取各种形式,如:ndarray,series,map,lists,dict,constant和另一个DataFrame。index
对于行标签,要用于结果帧的索引是可选缺省值np.arrange(n),如果没有传递索引值。columns
对于列标签,可选的默认语法是 - np.arange(n)。 这只有在没有索引传递的情况下才是这样。dtype
每列的数据类型。copy
如果默认值为False,则此命令(或任何它)用于复制数据。
Pandas数据帧(DataFrame)可以使用各种输入创建,如 -
- 列表
- 字典
- 系列
- Numpy ndarrays
- 另一个数据帧(DataFrame)
在本章的后续章节中,我们将看到如何使用这些输入创建数据帧(DataFrame)。
创建基本数据帧是空数据帧。
import pandas as pd
df = pd.DataFrame()
df
data = [1,2,3,4,5]
df = pd.DataFrame(data)
df
0 | |
---|---|
0 | 1 |
1 | 2 |
2 | 3 |
3 | 4 |
4 | 5 |
import pandas as pd
data = [['Alex',10],['Bob',12],['Clarke',13]]
df = pd.DataFrame(data,columns=['Name','Age'])
df
Name | Age | |
---|---|---|
0 | Alex | 10 |
1 | Bob | 12 |
2 | Clarke | 13 |
data = [['Alex',10],['Bob',12],['Clarke',13]]
df = pd.DataFrame(data,columns=['Name','Age'],dtype=float)
df
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) Cell In[5], line 2 1 data = [['Alex',10],['Bob',12],['Clarke',13]] ----> 2 df = pd.DataFrame(data,columns=['Name','Age'],dtype=float) 3 df File /opt/conda/lib/python3.12/site-packages/pandas/core/frame.py:859, in DataFrame.__init__(self, data, index, columns, dtype, copy) 850 columns = ensure_index(columns) 851 arrays, columns, index = nested_data_to_arrays( 852 # error: Argument 3 to "nested_data_to_arrays" has incompatible 853 # type "Optional[Collection[Any]]"; expected "Optional[Index]" (...) 857 dtype, 858 ) --> 859 mgr = arrays_to_mgr( 860 arrays, 861 columns, 862 index, 863 dtype=dtype, 864 typ=manager, 865 ) 866 else: 867 mgr = ndarray_to_mgr( 868 data, 869 index, (...) 873 typ=manager, 874 ) File /opt/conda/lib/python3.12/site-packages/pandas/core/internals/construction.py:119, in arrays_to_mgr(arrays, columns, index, dtype, verify_integrity, typ, consolidate) 116 index = ensure_index(index) 118 # don't force copy because getting jammed in an ndarray anyway --> 119 arrays, refs = _homogenize(arrays, index, dtype) 120 # _homogenize ensures 121 # - all(len(x) == len(index) for x in arrays) 122 # - all(x.ndim == 1 for x in arrays) (...) 125 126 else: 127 index = ensure_index(index) File /opt/conda/lib/python3.12/site-packages/pandas/core/internals/construction.py:629, in _homogenize(data, index, dtype) 626 val = dict(val) 627 val = lib.fast_multiget(val, oindex._values, default=np.nan) --> 629 val = sanitize_array(val, index, dtype=dtype, copy=False) 630 com.require_length_match(val, index) 631 refs.append(None) File /opt/conda/lib/python3.12/site-packages/pandas/core/construction.py:625, in sanitize_array(data, index, dtype, copy, allow_2d) 621 subarr = subarr.copy() 623 else: 624 # we will try to copy by-definition here --> 625 subarr = _try_cast(data, dtype, copy) 627 elif hasattr(data, "__array__"): 628 # e.g. dask array GH#38645 629 if not copy: File /opt/conda/lib/python3.12/site-packages/pandas/core/construction.py:820, in _try_cast(arr, dtype, copy) 818 subarr = maybe_cast_to_integer_array(arr, dtype) 819 elif not copy: --> 820 subarr = np.asarray(arr, dtype=dtype) 821 else: 822 subarr = np.array(arr, dtype=dtype, copy=copy) ValueError: could not convert string to float: 'Alex'
注意 - 可以观察到,dtype参数将Age列的类型更改为浮点。
所有的ndarrays必须具有相同的长度。如果传递了索引(index),则索引的长度应等于数组的长度。
如果没有传递索引,则默认情况下,索引将为range(n),其中n为数组长度。
data = {'Name':['Tom', 'Jack', 'Steve', 'Ricky'],'Age':[28,34,29,42]}
df = pd.DataFrame(data)
df
Name | Age | |
---|---|---|
0 | Tom | 28 |
1 | Jack | 34 |
2 | Steve | 29 |
3 | Ricky | 42 |
注 - 观察值0,1,2,3。它们是分配给每个使用函数range(n)的默认索引。
data = {'Name':['Tom', 'Jack', 'Steve', 'Ricky'],'Age':[28,34,29,42]}
df = pd.DataFrame(data, index=['rank1','rank2','rank3','rank4'])
df
Name | Age | |
---|---|---|
rank1 | Tom | 28 |
rank2 | Jack | 34 |
rank3 | Steve | 29 |
rank4 | Ricky | 42 |
注意 - index参数为每行分配一个索引。
字典列表可作为输入数据传递以用来创建数据帧(DataFrame),字典键默认为列名。
以下示例显示如何通过传递字典列表来创建数据帧(DataFrame)。
data = [{'a': 1, 'b': 2},{'a': 5, 'b': 10, 'c': 20}]
df = pd.DataFrame(data)
df
a | b | c | |
---|---|---|---|
0 | 1 | 2 | NaN |
1 | 5 | 10 | 20.0 |
注意 - 观察到,
NaN
(不是数字)被附加在缺失的区域。
以下示例显示如何通过传递字典列表和行索引来创建数据帧(DataFrame)。
data = [{'a': 1, 'b': 2},{'a': 5, 'b': 10, 'c': 20}]
df = pd.DataFrame(data, index=['first', 'second'])
df
a | b | c | |
---|---|---|---|
first | 1 | 2 | NaN |
second | 5 | 10 | 20.0 |
data = [{'a': 1, 'b': 2},{'a': 5, 'b': 10, 'c': 20}]
With two column indices, values same as dictionary keys
df1 = pd.DataFrame(data, index=['first', 'second'], columns=['a', 'b'])
With two column indices with one index with other name
df2 = pd.DataFrame(data, index=['first', 'second'], columns=['a', 'b1'])
print(df1)
print(df2)
注意 - 观察,df2使用字典键以外的列索引创建DataFrame; 因此,附加了NaN到位置上。 而df1是使用列索引创建的,与字典键相同,所以也附加了NaN。
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)
df
注意 - 对于第一个系列,观察到没有传递标签
d
,但在结果中,对于d
标签,附加了NaN
。
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)
df ['one']
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)
Adding a new column to an existing DataFrame object with column label by passing new series
print ("Adding a new column by passing as Series:")
df['three']=pd.Series([10,20,30],index=['a','b','c'])
print(df)
print ("Adding a new column using the existing columns in DataFrame:")
df['four']=df['one']+df['three']
print(df)
列可以删除或弹出; 看看下面的例子来了解一下。
# Using the previous DataFrame, we will delete a column
# using del function
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)
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'])
结果是一系列标签作为DataFrame的列名称。 而且,系列的名称是检索的标签。
按整数位置选择
可以通过将整数位置传递给iloc()函数来选择行。参考以下示例代码 -
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])
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])
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)
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)
# Drop rows with label 0
df = df.drop(0)
print(df)
在上面的例子中,一共有两行被删除,因为这两行包含相同的标签0。