需要注意的是DataFrame的数据源必须要是二位数组(字典就是一种二维数组)
例如:
import pandas
dic = {'Name':['Jack','Rose','Lucy'],'Score':[100,93,94],"Gender":["Male","Female","Female"]}
df = pandas.DataFrame(dic)
下面是DataFrame函数的参数:
data : ndarray (structured or homogeneous), Iterable, dict, or DataFrame
Dict can contain Series, arrays, constants, dataclass or list-like objects. If data is a dict, column order follows insertion-order. If a dict contains Series which have an index defined, it is aligned by its index.index : Index or array-like
Index to use for resulting frame. Will default to RangeIndex if no indexing information part of input data and no index provided.
columns : Index or array-likeColumn labels to use for resulting frame when data does not have them, defaulting to RangeIndex(0, 1, 2, ..., n). If data contains column labels, will perform column selection instead.
dtype : dtype, default None
Data type to force. Only a single dtype is allowed. If None, infer.
copy : bool or None, default None
Copy data from inputs. For dict data, the default of None behaves like copy=True. For DataFrame or 2d ndarray input, the default of None behaves like copy=False.
其中index指最左边一列的编号,column指最上面一排的编号,如果不设置都是默认0-n。最后一个参数则是是否从输入中复制,为一个布尔值,一般不会用到。
二、插入行如果要修改列的编号,代码如下:
import pandas dic = {'Name':['Jack','Rose','Lucy'],'Score':[100,93,94],"Gender":["Male","Female","Female"]} df = pandas.DataFrame(dic) print(df) df = pandas.DataFrame(dic,index=[8,7,8]) print(df)对应效果:
从末尾加入使用的是append函数
下面是append函数的参数:
Parametersother : DataFrame or Series/dict-like object, or list of these
Returns
The data to append.
ignore_index : bool, default False
If True, the resulting axis will be labeled 0, 1, …, n - 1.
verify_integrity : bool, default False
If True, raise ValueError on creating index with duplicates.
sort : bool, default False
Sort columns if the columns of self and other are not aligned.DataFrame
See Also
A new DataFrame consisting of the rows of caller and the rows of other.concat : General function to concatenate DataFrame or Series objects.
NotesIf a list of dict/series is passed and the keys are all contained in the DataFrame's index, the order of the columns in the resulting DataFrame will be unchanged.
Iteratively appending rows to a DataFrame can be more computationally intensive than a single concatenate. A better solution is to append those rows to a list and then concatenate the list with the original DataFrame all at once.
可以看到的是该函数是有返回值的,且是“ A new DataFrame consisting of the rows of caller and the rows of other.“,即修改过后的DataFrame,所以我们要用新的变量去”接受“它。
下面是实现代码:
import pandas dic = {'Name':['Jack','Rose','Lucy'],'Score':[100,93,94],"Gender":["Male","Female","Female"]} df = pandas.DataFrame(dic) print(df) df2 = df.append({"Name":"Luara","Score":99,"Gender":"Female"}, ignore_index=True) print(df2)对应效果:
需要注意的是,如果append的是一个字典的话ignore_index 必须为True,否则会报错



