第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問(wèn)題,去搜搜看,總會(huì)有你想問(wèn)的

如何在不迭代的情況下根據(jù)特定對(duì)從數(shù)據(jù)框中選擇結(jié)果?

如何在不迭代的情況下根據(jù)特定對(duì)從數(shù)據(jù)框中選擇結(jié)果?

倚天杖 2021-12-17 15:46:47
我想根據(jù)某些特定對(duì)從數(shù)據(jù)幀中查詢(或定位)子數(shù)據(jù)幀。使用迭代很容易做到這一點(diǎn),但速度很慢。import pandas as pddf=pd.DataFrame([[1,2,3], [1,5,6], [7,8,9], [2,3,8]], columns=['x','y','z'])dfOut[4]:    x  y  z0  1  2  31  1  5  62  7  8  93  2  3  8我想得到一個(gè)子數(shù)據(jù)框,其中 (x,y)=(1,2) 和 (x,y)=(1,5) 和 (x,y)=(2,3),如下所示Out[5]:    x  y  z0  1  2  31  1  5  63  2  3  8我的方法是使用迭代來(lái)獲取索引:xy_list=[(1,2),(1,5),(2,3)]index_list=[]for x,y in xy_list:    index_list+=df.query('x==@x & y==@y').index.tolist()df_sub=df.loc[index_list]df_subOut[6]:    x  y  z0  1  2  31  1  5  63  2  3  8有沒(méi)有什么方法可以在不使用迭代的情況下做到這一點(diǎn)?
查看完整描述

2 回答

?
慕村9548890

TA貢獻(xiàn)1884條經(jīng)驗(yàn) 獲得超4個(gè)贊

你很接近,但你不需要query反復(fù)調(diào)用。只需使用構(gòu)建您的查詢字符串str.join并query在之后進(jìn)行一次調(diào)用。


data = [(1, 2), (1, 5), (2, 3)]


pattern = '(' + ') | ('.join(f"x == {a} & y == " for a, b in data) + ')'

pattern

# '(x == 1 & y == 2) | (x == 1 & y == 5) | (x == 2 & y == 3)'


df.query(pattern)


   x  y  z

0  1  2  3

1  1  5  6

3  2  3  8

另一種選擇是使用Index.isin和一些過(guò)濾:


df[df.set_index(['x', 'y']).index.isin(data)]


   x  y  z

0  1  2  3

1  1  5  6

3  2  3  8

或者,使用MultiIndex.from_arrays以下方法構(gòu)建 MultiIndex :


df[pd.MultiIndex.from_arrays([df['x'], df['y']]).isin(data)]


   x  y  z

0  1  2  3

1  1  5  6

3  2  3  8

結(jié)果相同,效率更高。


查看完整回答
反對(duì) 回復(fù) 2021-12-17
?
婷婷同學(xué)_

TA貢獻(xiàn)1844條經(jīng)驗(yàn) 獲得超8個(gè)贊

或者你可以做一個(gè)df.set_index()and df.loc[]:


xy_list=[(1,2),(1,5),(2,3)]

df_new=df.set_index(['x','y']).loc[xy_list].reset_index()

   x  y  z

0  1  2  3

1  1  5  6

2  2  3  8


查看完整回答
反對(duì) 回復(fù) 2021-12-17
  • 2 回答
  • 0 關(guān)注
  • 173 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)