網(wǎng)站首頁 編程語言 正文
當使用for語句循環(huán)(迭代)pandas.DataFrame時,簡單的使用for語句便可以取得返回列名,因此使用重復(fù)使用for方法,便可以獲取每行的值。
以下面的pandas.DataFrame為例。
import pandas as pd
df = pd.DataFrame({'age': [24, 42], 'state': ['NY', 'CA'], 'point': [64, 92]},
? ? ? ? ? ? ? ? ? index=['Alice', 'Bob'])
print(df)
# ? ? ? ?age state ?point
# Alice ? 24 ? ?NY ? ? 64
# Bob ? ? 42 ? ?CA ? ? 92
在此對以下內(nèi)容進行說明:
- pandas.DataFrame for循環(huán)的應(yīng)用
- 逐列檢索
- DataFrame.iteritems()
- 逐行檢索
- DataFrame.iterrows()
- DataFrame.itertuples()
- 檢索特定列的值
- 循環(huán)更新值
pandas.DataFrame for循環(huán)的應(yīng)用
當pandas.DataFrame直接使用for循環(huán)時,按以下順序獲取列名(列名)。
for column_name in df:
print(type(column_name))
print(column_name)
print('======\n')
# <class 'str'>
# age
# ======
#
# <class 'str'>
# state
# ======
#
# <class 'str'>
# point
# ======
#
調(diào)用方法__iter __()。
for column_name in df.__iter__():
print(type(column_name))
print(column_name)
print('======\n')
# <class 'str'>
# age
# ======
#
# <class 'str'>
# state
# ======
#
# <class 'str'>
# point
# ======
#
逐列檢索
DataFrame.iteritems()
使用iteritems()方法,您可以一一獲取列名稱(列名稱)和元組(列名稱,系列)的每個列的數(shù)據(jù)(pandas.Series類型)。
pandas.Series可以通過指定索引名稱等來檢索行的值。
for column_name, item in df.iteritems():
? ? print(type(column_name))
? ? print(column_name)
? ? print('~~~~~~')
? ? print(type(item))
? ? print(item)
? ? print('------')
? ? print(item['Alice'])
? ? print(item[0])
? ? print(item.Alice)
? ? print('======\n')
# <class 'str'>
# age
# ~~~~~~
# <class 'pandas.core.series.Series'>
# Alice ? ?24
# Bob ? ? ?42
# Name: age, dtype: int64
# ------
# 24
# 24
# 24
# ======
#?
# <class 'str'>
# state
# ~~~~~~
# <class 'pandas.core.series.Series'>
# Alice ? ?NY
# Bob ? ? ?CA
# Name: state, dtype: object
# ------
# NY
# NY
# NY
# ======
#?
# <class 'str'>
# point
# ~~~~~~
# <class 'pandas.core.series.Series'>
# Alice ? ?64
# Bob ? ? ?92
# Name: point, dtype: int64
# ------
# 64
# 64
# 64
# ======
#?
逐行檢索
一次檢索一行的方法包括iterrows()和itertuples()。 itertuples()更快。
如果只需要特定列的值,則如下所述,指定列并將它們分別在for循環(huán)中進行迭代會更快。
DataFrame.iterrows()
通過使用iterrows()方法,可以獲得每一行的數(shù)據(jù)(pandas.Series類型)和行名和元組(索引,系列)。
pandas.Series可以通過指定列名等來檢索列的值。
for index, row in df.iterrows():
? ? print(type(index))
? ? print(index)
? ? print('~~~~~~')
? ? print(type(row))
? ? print(row)
? ? print('------')
? ? print(row['point'])
? ? print(row[2])
? ? print(row.point)
? ? print('======\n')
# <class 'str'>
# Alice
# ~~~~~~
# <class 'pandas.core.series.Series'>
# age ? ? ?24
# state ? ?NY
# point ? ?64
# Name: Alice, dtype: object
# ------
# 64
# 64
# 64
# ======
#?
# <class 'str'>
# Bob
# ~~~~~~
# <class 'pandas.core.series.Series'>
# age ? ? ?42
# state ? ?CA
# point ? ?92
# Name: Bob, dtype: object
# ------
# 92
# 92
# 92
# ======
DataFrame.itertuples()
使用itertuples()方法,可以一一獲取索引名(行名)和該行數(shù)據(jù)的元組。元組的第一個元素是索引名稱。
默認情況下,返回一個名為Pandas的namedtuple。由于它是namedtuple,因此可以訪問每個元素的值。
for row in df.itertuples():
? ? print(type(row))
? ? print(row)
? ? print('------')
? ? print(row[3])
? ? print(row.point)
? ? print('======\n')
# <class 'pandas.core.frame.Pandas'>
# Pandas(Index='Alice', age=24, state='NY', point=64)
# ------
# 64
# 64
# ======
#?
# <class 'pandas.core.frame.Pandas'>
# Pandas(Index='Bob', age=42, state='CA', point=92)
# ------
# 92
# 92
# ======
#?
如果參數(shù)name為None,則返回一個普通的元組。
for row in df.itertuples(name=None):
? ? print(type(row))
? ? print(row)
? ? print('------')
? ? print(row[3])
? ? print('======\n')
# <class 'tuple'>
# ('Alice', 24, 'NY', 64)
# ------
# 64
# ======
#?
# <class 'tuple'>
# ('Bob', 42, 'CA', 92)
# ------
# 92
# ======
檢索特定列的值
上述的iterrows()和itertuples()方法可以檢索每一行中的所有列元素,但是如果僅需要特定的列元素,可以使用以下方法。
pandas.DataFrame的列是pandas.Series。
print(df['age'])
# Alice ? ?24
# Bob ? ? ?42
# Name: age, dtype: int64
print(type(df['age']))
# <class 'pandas.core.series.Series'>
如果將pandas.Series應(yīng)用于for循環(huán),則可以按順序獲取值,因此,如果指定pandas.DataFrame列并將其應(yīng)用于for循環(huán),則可以按順序獲取該列中的值。
for age in df['age']:
print(age)
# 24
# 42
如果使用內(nèi)置函數(shù)zip(),則可以一次收集多列值。
for age, point in zip(df['age'], df['point']):
print(age, point)
# 24 64
# 42 92
如果要獲取索引(行名),使用index屬性。如以上示例所示,可以與其他列一起通過zip()獲得。
print(df.index)
# Index(['Alice', 'Bob'], dtype='object')
print(type(df.index))
# <class 'pandas.core.indexes.base.Index'>
for index in df.index:
? ? print(index)
# Alice
# Bob
for index, state in zip(df.index, df['state']):
? ? print(index, state)
# Alice NY
# Bob CA
循環(huán)更新值
iterrows()方法逐行檢索值,返回一個副本,而不是視圖,因此更改pandas.Series不會更新原始數(shù)據(jù)。
for index, row in df.iterrows():
? ? row['point'] += row['age']
print(df)
# ? ? ? ?age state ?point
# Alice ? 24 ? ?NY ? ? 64
# Bob ? ? 42 ? ?CA ? ? 92
at[]選擇并處理原始DataFrame中的數(shù)據(jù)時更新。
for index, row in df.iterrows():
? ? df.at[index, 'point'] += row['age']
print(df)
# ? ? ? ?age state ?point
# Alice ? 24 ? ?NY ? ? 88
# Bob ? ? 42 ? ?CA ? ?134
有關(guān)at[]的文章另請參考以下連接。
Pandas獲取和修改任意位置的值(at,iat,loc,iloc)
請注意,上面的示例使用at[]只是一個示例,在許多情況下,有必要使用for循環(huán)來更新元素或基于現(xiàn)有列添加新列,for循環(huán)的編寫更加簡單快捷。
與上述相同的處理。上面更新的對象被進一步更新。
df['point'] += df['age']
print(df)
# age state point
# Alice 24 NY 112
# Bob 42 CA 176
可以添加新列。
df['new'] = df['point'] + df['age'] * 2
print(df)
# age state point new
# Alice 24 NY 112 160
# Bob 42 CA 176 260
除了簡單的算術(shù)運算之外,NumPy函數(shù)還可以應(yīng)用于列的每個元素。以下是平方根的示例。另外,這里,NumPy的功能可以通過pd.np訪問,但是,當然可以單獨導(dǎo)入NumPy。
df['age_sqrt'] = pd.np.sqrt(df['age'])
print(df)
# age state point new age_sqrt
# Alice 24 NY 112 160 4.898979
# Bob 42 CA 176 260 6.480741
?對于字符串,提供了用于直接處理列(系列)的字符串方法。下面是轉(zhuǎn)換為小寫并提取第一個字符的示例。
df['state_0'] = df['state'].str.lower().str[0]
print(df)
# age state point new age_sqrt state_0
# Alice 24 NY 112 160 4.898979 n
# Bob 42 CA 176 260 6.480741 c
原文鏈接:https://blog.csdn.net/qq_18351157/article/details/105261636
- 上一篇:沒有了
- 下一篇:沒有了
相關(guān)推薦
- 2023-05-08 Python實現(xiàn)統(tǒng)計文章閱讀量的方法詳解_python
- 2022-04-07 Swift實現(xiàn)簡易計算器功能_Swift
- 2022-03-26 C++缺省參數(shù)的具體使用_C 語言
- 2022-08-27 Python+matplotlib繪制多子圖的方法詳解_python
- 2021-12-05 Go語言配置數(shù)據(jù)庫連接池的實現(xiàn)_Golang
- 2022-05-27 Python/R語言分別實現(xiàn)斐波那契數(shù)列的示例詳解_python
- 2022-09-17 Pandas中df.loc[]與df.iloc[]的用法與異同?_python
- 2022-12-24 提升Go語言開發(fā)效率的小技巧實例(GO語言語法糖)匯總_Golang
- 欄目分類
-
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細win安裝深度學習環(huán)境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡單動態(tài)字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支