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

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

如何在 fstrings 中使用 .loc?

如何在 fstrings 中使用 .loc?

哈士奇WWW 2021-06-28 13:35:04
我有一個(gè)這樣的數(shù)據(jù)框:import pandas as pddf = pd.DataFrame({'col1': ['abc', 'def', 'tre'],                   'col2': ['foo', 'bar', 'stuff']})  col1   col20  abc    foo1  def    bar2  tre  stuff和這樣的字典:d = {'col1': [0, 2], 'col2': [1]}字典包含要從數(shù)據(jù)框中提取的列名和值索引,以生成如下字符串:abc (0, col1)因此,每個(gè)字符串都以元素本身開頭,并在括號(hào)中顯示索引和列名。我嘗試了以下列表理解:l = [f"{df.loc[{indi}, {ci}]} ({indi}, {ci})"     for ci, vali in d.items()     for indi in vali]這產(chǎn)生['  col1\n0  abc (0, col1)', '  col1\n2  tre (2, col1)', '  col2\n1  bar (1, col2)']所以,幾乎沒問題,只是col1\n0需要避免的部分。如果我嘗試f"{df.loc[0, 'col1']} is great"我得到'abc is great'然而,根據(jù)需要,x = 0f"{df.loc[{x}, 'col1']} is great"我得到'0    abc\nName: col1, dtype: object is great'這怎么能解決?
查看完整描述

2 回答

?
翻閱古今

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

import pandas as pd


df = pd.DataFrame({'col1': ['abc', 'def', 'tre'],

                   'col2': ['foo', 'bar', 'stuff']})


d = {'col1': [0, 2], 'col2': [1]}

x = 0

[f"{df.loc[x, 'col1']} is great"

     for ci, vali in d.items()

     for indi in vali]

這給了你:


['abc is great', 'abc is great', 'abc is great']

這是你要找的嗎?


你也可以循環(huán)通過 x 范圍

[f"{df.loc[i, 'col1']} is great"

 for ci, vali in d.items()

 for indi in vali

 for i in range(2)]


#output

['abc is great',

 'def is great',

 'abc is great',

 'def is great',

 'abc is great',

 'def is great']


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

添加回答

舉報(bào)

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號(hào)

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