網(wǎng)站首頁(yè) 編程語(yǔ)言 正文
當(dāng)使用for語(yǔ)句循環(huán)(迭代)pandas.DataFrame時(shí),簡(jiǎn)單的使用for語(yǔ)句便可以取得返回列名,因此使用重復(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
在此對(duì)以下內(nèi)容進(jìn)行說(shuō)明:
- pandas.DataFrame for循環(huán)的應(yīng)用
- 逐列檢索
- DataFrame.iteritems()
- 逐行檢索
- DataFrame.iterrows()
- DataFrame.itertuples()
- 檢索特定列的值
- 循環(huán)更新值
pandas.DataFrame for循環(huán)的應(yīng)用
當(dāng)pandas.DataFrame直接使用for循環(huán)時(shí),按以下順序獲取列名(列名)。
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()方法,您可以一一獲取列名稱(列名稱)和元組(列名稱,系列)的每個(gè)列的數(shù)據(jù)(pandas.Series類型)。
pandas.Series可以通過(guò)指定索引名稱等來(lái)檢索行的值。
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)中進(jìn)行迭代會(huì)更快。
DataFrame.iterrows()
通過(guò)使用iterrows()方法,可以獲得每一行的數(shù)據(jù)(pandas.Series類型)和行名和元組(索引,系列)。
pandas.Series可以通過(guò)指定列名等來(lái)檢索列的值。
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ù)的元組。元組的第一個(gè)元素是索引名稱。
默認(rèn)情況下,返回一個(gè)名為Pandas的namedtuple。由于它是namedtuple,因此可以訪問(wèn)每個(gè)元素的值。
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,則返回一個(gè)普通的元組。
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屬性。如以上示例所示,可以與其他列一起通過(guò)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()方法逐行檢索值,返回一個(gè)副本,而不是視圖,因此更改pandas.Series不會(huì)更新原始數(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ù)時(shí)更新。
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[]的文章另請(qǐng)參考以下連接。
Pandas獲取和修改任意位置的值(at,iat,loc,iloc)
請(qǐng)注意,上面的示例使用at[]只是一個(gè)示例,在許多情況下,有必要使用for循環(huán)來(lái)更新元素或基于現(xiàn)有列添加新列,for循環(huán)的編寫更加簡(jiǎn)單快捷。
與上述相同的處理。上面更新的對(duì)象被進(jì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
除了簡(jiǎn)單的算術(shù)運(yùn)算之外,NumPy函數(shù)還可以應(yīng)用于列的每個(gè)元素。以下是平方根的示例。另外,這里,NumPy的功能可以通過(guò)pd.np訪問(wèn),但是,當(dāng)然可以單獨(dú)導(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
?對(duì)于字符串,提供了用于直接處理列(系列)的字符串方法。下面是轉(zhuǎn)換為小寫并提取第一個(gè)字符的示例。
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
- 上一篇:沒(méi)有了
- 下一篇:沒(méi)有了
相關(guān)推薦
- 2022-07-27 Python中range函數(shù)的使用方法_python
- 2022-06-14 Redis高并發(fā)情況下并發(fā)扣減庫(kù)存項(xiàng)目實(shí)戰(zhàn)_Redis
- 2022-04-19 基于HarmonyOS的ArkUI編寫的社區(qū)類app(四)———倒計(jì)時(shí)控制和驗(yàn)證碼登錄功能的實(shí)現(xiàn)
- 2022-09-24 python的numpy模塊實(shí)現(xiàn)邏輯回歸模型_python
- 2022-08-02 flask后端request獲取參數(shù)的幾種方式整理_python
- 2022-06-30 Oracle在PL/SQL中使用子查詢_oracle
- 2022-06-21 Android?使用flow實(shí)現(xiàn)倒計(jì)時(shí)的方式_Android
- 2023-05-29 React優(yōu)雅的封裝SvgIcon組件示例_React
- 欄目分類
-
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細(xì)win安裝深度學(xué)習(xí)環(huán)境2025年最新版(
- Linux 中運(yùn)行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲(chǔ)小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運(yùn)算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認(rèn)證信息的處理
- Spring Security之認(rèn)證過(guò)濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯(cuò)誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實(shí)現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡(jiǎn)單動(dòng)態(tài)字符串(SD
- arthas操作spring被代理目標(biāo)對(duì)象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊(duì)列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠(yuǎn)程分支