欢迎光临
我们一直在努力

如何向Pandas中的DataFrame添加行

这篇文章给大家分享的是有关如何向Pandas中的DataFrame添加行的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。

您可以使用df.loc()函数在Pandas DataFrame的末尾添加一行:

#add row to end of DataFrame
df.loc[len(df.index)] = [value1, value2, value3, ...]

您可以使用df.append()函数将现有 DataFrame 的几行附加到另一个 DataFrame 的末尾:

#append rows of df2 to end of existing DataFrame
df = df.append(df2, ignore_index = True)

下面的例子展示了如何在实践中使用这些函数。

示例 1:向 Pandas DataFrame 添加一行

以下代码显示了如何在 Pandas 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 的几行添加到另一个 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 应该具有相同的列名,以便成功地将一个 DataFrame 的行附加到另一个 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添加行”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!

赞(0)
【声明】:本博客不参与任何交易,也非中介,仅记录个人感兴趣的主机测评结果和优惠活动,内容均不作直接、间接、法定、约定的保证。访问本博客请务必遵守有关互联网的相关法律、规定与规则。一旦您访问本博客,即表示您已经知晓并接受了此声明通告。