深度阅读

How to append a new row to a Pandas DataFrame?

作者
作者
2023年08月22日
更新时间
14.84 分钟
阅读时间
0
阅读量

To append a new row to a Pandas DataFrame, you can use the append() method. Here’s an example:

import pandas as pd

df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]}) # create a DataFrame with columns A and B
new_row = {'A': 4, 'B': 7} # create a dictionary representing the new row to be added
df = df.append(new_row, ignore_index=True) # append the new row to the DataFrame
print(df)

Output:

   A  B
0  1  4
1  2  5
2  3  6
3  4  7

In the example above, new_row stores a dictionary representing the new row we want to add to the DataFrame. The append() method adds the new row to the DataFrame, ignoring the original index and using a new index instead. The modified DataFrame is then stored back into the original DataFrame.

Note that if you want to preserve the index of the original DataFrame, you can set the ignore_index argument to False:

df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]}) # create a DataFrame with columns A and B
new_row = {'A': 4, 'B': 7} # create a dictionary representing the new row to be added
df = df.append(new_row, ignore_index=False) # append the new row to the DataFrame, preserving the original index
print(df)

Output:

   A  B
0  1  4
1  2  5
2  3  6
3  4  7

In summary, to append a new row to a Pandas DataFrame, create a dictionary representing the new row, then use the append() method to add the row to the DataFrame, either preserving or ignoring the original index as desired.

相关标签

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。