网络编程
位置:首页>> 网络编程>> Python编程>> 一文教你向Pandas DataFrame添加行

一文教你向Pandas DataFrame添加行

作者:allway2  发布时间:2022-01-31 13:51:01 

标签: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

pointsrebounds assists
0107 11
1127 8
2128 10
31413 6
4137 6
5184 5

#add new row to end of DataFrame
df.loc[len(df.index)] = [20, 7, 5]

#view updated DataFrame
df

pointsrebounds assists
0107 11
1127 8
2128 10
31413 6
4137 6
5184 5
6207 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

pointsrebounds assists
0107 11
1127 8
2128 10
31413 6
4137 6
5184 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

pointsrebounds assists
0107 11
1127 8
2128 10
31413 6
4137 6
5184 5
6217 11
7257 3
82613 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

来源:https://blog.csdn.net/allway2/article/details/121421241

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com