簡體   English   中英

將 Python pandas DataFrame 列值映射到其他值

[英]Mapping Python pandas DataFrame column values to other values

我有一個帶有targets列的 dataframe ,我將它們分配給y

y = df['targets']

0         APPLE
1         APPLE
2        ORANGE
3         APPLE
4         APPLE
         ...  
9995     ORANGE
9996     ORANGE
9997      APPLE
9998     ORANGE
9999     ORANGE
Name: class, Length: 10000, dtype: object

我需要將我的分類特征更改為int並為此構建了一個dict ,所有分類特征作為keyint作為value

target_mapping = {
    'APPLE': 0,
    'ORANGE': 1,
    'AVACADO': 2
}

如何使用.map function 更改y中的值?

預期的 output 應如下所示:

0         0
1         0
2         1
3         0
4         0
         ...  
9995      1
9996      1
9997      0
9998      1
9999      1
Name: class, Length: 10000, dtype: object

一種解決方案:

import pandas as pd

target_mapping = {
    'APPLE': 0,
    'ORANGE': 1,
    'AVOCADO': 2
}
df = pd.DataFrame({"targets": ["APPLE", "ORANGE", "ORANGE", "AVOCADO"]})
df["targets"] = df["targets"].map(lambda x: target_mapping[x])

NB1我將帖子AVACADO的單詞替換為AVOCADO (我認為這是一個錯字)

NB2該解決方案假定target_mapping鍵與df["target"]中的所有可能值相同

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM