df = df.append(new_row, ignore_index=True) 在append()方法中,ignore_index=True参数会重新设置索引。 使用loc属性: import pandas as pd # 创建一个DataFrame df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]}) # 添加新行 new_row = pd.Series([7, 8]) df.loc[len(df)] =...
示例代码1:使用append()追加单行 importpandasaspd# 创建一个DataFramedf=pd.DataFrame({'Name':['Alice','Bob'],'Website':['pandasdataframe.com','pandasdataframe.com'],'Age':[25,30]})# 创建一个Series,作为新行new_row=pd.Series(['Charlie','pandasdataframe.com',35],index=df.columns)# 追加...
以下列出了常用的方法:使用 append() 方法:import pandas as pd# 创建示例数据data = {'A': [1, 2, 3], 'B': [4, 5, 6]}df = pd.DataFrame(data)# 创建新行new_row1 = {'A': 7, 'B': 8}# 使用 append() 方法追加新行df = df.append(new_row, ignore_index=True)print(df)输出...
df = df.append(new_row, ignore_index=True) print("\nDataFrame after appending a single row:") print(df) 2)追加多行数据(DataFrame) importpandasaspd# 创建一个 DataFramedf = pd.DataFrame({'A': [1,2,3],'B': [4,5,6]}) print("Original DataFrame:") print(df)# 追加多行数据(DataFr...
df = df.append(new_row.to_frame().T) print(df) 注意,append()方法返回一个新的DataFrame,并不会修改原来的DataFrame。所以你需要将结果赋值回原来的变量。 2. 使用loc或iloc索引 如果你知道要添加行的位置,你可以直接使用loc或iloc来在指定位置插入一行。这要求你创建一个新的DataFrame,其大小与原始DataFrame...
importpandasaspd# 创建一个 DataFramedf=pd.DataFrame({'Website':['pandasdataframe.com'],'Pageviews':[1000],'Users':[100]})# 使用字典添加新行new_row={'Website':'pandasdataframe.com','Pageviews':1600,'Users':130}# 添加新行df=df._append(new_row,ignore_index=True)print(df) ...
创建新的DataFrame追加至原有数据帧的尾部,即可实现行的增加。通过df.append()实现行的追加。 #创建新的数据帧df_row3 = pd.DataFrame([[4,'D','9%']], index=['row_3'], columns=['col_0','col_1','col_2'])#追加至原有数据帧尾部df = df.append(df_row3) ...
importpandasaspd# 创建一个初始DataFramedf=pd.DataFrame({'Name':['Alice','Bob'],'Website':['pandasdataframe.com','pandasdataframe.com'],'Age':[25,30]})# 创建一个字典,表示要添加的新行new_row={'Name':'Charlie','Website':'pandasdataframe.com','Age':35}# 使用append()添加新行df=df...
df2 = df.append(new_row, ignore_index=True) df2 首先创建了一个DataFrame df,然后创建了一个新的DataFrame new_row,最后使用append()函数将 new_row 添加到 df 的末尾。ignore_index=True 的参数可以让新的DataFrame忽略原始的索引,并生成一个新的从0开始的索引。
在这个例子中,我们首先创建了一个空的数据框df,然后创建了一个带有列表的数据框new_row,其中'A'列的值为[1, 2, 3],'B'列的值为[4, 5, 6]。接着,我们使用append()方法将new_row追加到df的末尾,并将结果重新赋值给df。最后,我们打印输出了df的内容,可以看到new_row成功追加为df的一行。