亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Python/Pandas:獲取列中項目的索引

Python/Pandas:獲取列中項目的索引

慕田峪9158850 2023-04-18 15:08:24
我有一個包含以下列的 Pandas dataframe(df):df["ids"]0         18281483,16583915471           1268212,1280644302                  13465424253  13591493,13123669,35938208df[“編號”]0      182814831       12682122    13465424253      13123669我想找出“ids”的哪個順序可以找到相應的“id”,并在新列“order”中輸出相應的值。嘗試了以下代碼但沒有成功:df["order"] = df["ids"].str.split(",").index(df["id"])----------------------------------------------------------------------TypeError: 'Int64Index' object is not callable有語法錯誤嗎?我手動嘗試了對每一行的拆分和索引函數(通過插入列表和字符串),它起作用了。期望的輸出:df[“訂單”]0 01 02 0 3 1
查看完整描述

3 回答

?
小怪獸愛吃肉

TA貢獻1852條經驗 獲得超1個贊

嘗試:


df['output'] = df.astype(str).apply(lambda x: x['ids'].split(',').index(x['id']), axis=1)

輸出:


                          ids          id  output

0         18281483,1658391547    18281483       0

1           1268212,128064430     1268212       0

2                  1346542425  1346542425       0

3  13591493,13123669,35938208    13123669       1


查看完整回答
反對 回復 2023-04-18
?
aluckdog

TA貢獻1847條經驗 獲得超7個贊

這是一種方法,


def index_(ids, id):

    split_ = ids.split(",")

    if id in split_:

        return split_.index(id)

    else:

        return -1



print(

    df.assign(id = df1.id.astype(str))

        .apply(lambda x: index_(x.ids, x.id), axis=1)

)

0    0

1    0

2    0

3    1

dtype: int64


查看完整回答
反對 回復 2023-04-18
?
慕絲7291255

TA貢獻1859條經驗 獲得超6個贊

真的不應該apply在這里使用。在更大的 Dataframes 上,它會非常慢。廣播比較會工作得很好。


(df["ids"].str.split(",", expand=True) == df["id"][:, None]).idxmax(1)

0    0

1    0

2    0

3    1

dtype: int64

表現


d = {'ids': {0: '18281483,1658391547',

             1: '1268212,128064430',

             2: '1346542425',

             3: '13591493,13123669,35938208'},

      'id': {0: '18281483', 

             1: '1268212', 

             2: '1346542425',

             3: '13123669'}}


df = pd.DataFrame(d)

df = pd.concat([df] * 1000)


%timeit (df["ids"].str.split(",", expand=True) == df["id"][:, None]).idxmax(1)                 

7.51 ms ± 61.4 μs per loop (mean ± std. dev. of 7 runs, 100 loops each)


%timeit df.apply(lambda x: x['ids'].split(',').index(x['id']), axis=1)                         

54.1 ms ± 249 μs per loop (mean ± std. dev. of 7 runs, 10 loops each)


查看完整回答
反對 回復 2023-04-18
  • 3 回答
  • 0 關注
  • 303 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號