網站首頁 編程語言 正文
引言
您可以使用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
總結
原文鏈接:https://blog.csdn.net/allway2/article/details/121421241
相關推薦
- 2022-07-09 Jquery操作DOM元素方法詳解_jquery
- 2022-03-05 CentOS系統下安裝及配置JDK介紹_Linux
- 2022-06-01 C語言線性表中順序表超詳細理解_C 語言
- 2022-07-21 SpringCache 面向注解開發
- 2022-12-21 使用RedisAtomicInteger計數出現少計問題及解決_Redis
- 2023-07-24 E6新語法for of 和ES3的for in 有什么區別?useState為什么是用數組結構而不用
- 2022-04-12 el-form表單驗證的一些方法總結
- 2022-10-16 Python?re.split方法分割字符串的實現示例_python
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支