Pandas DataFrame 添加行与列的完整指南:loc与append用法详解
本文详细介绍在Pandas DataFrame中高效添加数据的方法。通过df.loc()函数在末尾添加单行,以及使用df.append()合并多个DataFrame的行。文章提供Python代码示例,演示如何操作points、rebounds等列,并补充优雅添加单列的技巧,帮助开发者掌握数据增补的核心操作。
引言
在数据处理过程中,经常需要在现有的Pandas DataFrame末尾追加新数据。实现这一操作最直接且常用的方法是利用df.loc()函数,通过指定索引位置来插入新的一行数据。
#add row to end of DataFrame
df.loc[len(df.index)] = [value1, value2, value3, ...]另一种常见场景是将一个现有DataFrame的多行数据追加到另一个DataFrame的末尾。此时,可以使用df.append()函数完成这一合并操作,确保两个数据源的结构兼容。
#append rows of df2 to end of existing DataFrame
df = df.append(df2, ignore_index = True)
为了更直观地理解上述方法,下面将通过具体的代码示例,展示如何在实际编程中应用这些函数进行数据添加操作。
示例 1:向 Pandas DataFrame 添加一行
以下代码演示了如何在Pandas DataFrame的末尾成功添加一行数据。首先创建包含points、rebounds和assists列的基础DataFrame,然后利用df.loc[len(df.index)]指定新行的索引位置,并赋值相应的数据列表。最后查看更新后的DataFrame,确认新行已成功添加至末尾。
import pandas as pd
#create DataFrame
df = pd.DataFrame({'points': [10, 12, 12, 14, 13, 18],
'rebounds': [7, 7, 8, 13, 7, 4],
'assists': [11, 8, 10, 6, 6, 5]})
#view DataFrame
df
points rebounds assists
0 10 7 11
1 12 7 8
2 12 8 10
3 14 13 6
4 13 7 6
5 18 4 5
#add new row to end of DataFrame
df.loc[len(df.index)] = [20, 7, 5]
#view updated DataFrame
df
points rebounds assists
0 10 7 11
1 12 7 8
2 12 8 10
3 14 13 6
4 13 7 6
5 18 4 5
6 20 7 5示例 2:向 Pandas DataFrame 添加几行
以下代码展示了如何将另一个DataFrame(df2)中的多行数据追加到现有DataFrame(df)的末尾。关键在于使用df.append()函数,并设置ignore_index=True以重置索引。代码首先定义了两个具有相同列结构的DataFrame,执行追加操作后,查看更新结果,验证数据是否正确合并。
import pandas as pd
#create DataFrame
df = pd.DataFrame({'points': [10, 12, 12, 14, 13, 18],
'rebounds': [7, 7, 8, 13, 7, 4],
'assists': [11, 8, 10, 6, 6, 5]})
#view DataFrame
df
points rebounds assists
0 10 7 11
1 12 7 8
2 12 8 10
3 14 13 6
4 13 7 6
5 18 4 5
#define second DataFrame
df2 = pd.DataFrame({'points': [21, 25, 26],
'rebounds': [7, 7, 13],
'assists': [11, 3, 3]})
#add new row to end of DataFrame
df = df.append(df2, ignore_index = True)
#view updated DataFrame
df
points rebounds assists
0 10 7 11
1 12 7 8
2 12 8 10
3 14 13 6
4 13 7 6
5 18 4 5
6 21 7 11
7 25 7 3
8 26 13 3需要注意的是,在执行追加操作前,必须确保两个DataFrame具有相同的列名。如果列名不一致,追加操作可能会失败或产生非预期的结果。因此,保持数据结构的一致性是实现成功合并的前提条件。
补充:优雅的增加一列,一定要优雅!
df['new_colu']='12'#向 DataFrame 添加一列,该列为同一值
df
Out[93]:
one two three four new_colu
a 0 1 2 3 12
b 4 5 6 7 12
c 8 9 10 11 12
d 12 13 14 15 12
new_raw 3 3 3 3 12
总结
到此这篇关于向Pandas DataFrame添加行的文章就介绍到这了,更多相关Pandas DataFrame添加行内容请搜索本站以前的文章或继续浏览下面的相关文章希望大家以后多多支持本站!
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









