[英]Create new column in DataFrame based on respective values in two different columns
[英]Best way to create a new columns of numerics based on different string values in different column?
我在 3 列中有 5 個不同的可能字符串值,我想將它們轉換為 3 個新列中的數值。
Columns:
1_month, 6_month, 12_month
Possible Values:
High
Above Average
Average
Below Average
Low
I'd like to create 3 new columns:
1_month_int, 6_month_int, 12_month_int
Then map the numerics from the string values as:
High = 5
Above Average = 4
Average = 3
Below Average = 2
Low = 1
我嘗試復制該列,然后查找並替換單個列的值,然后在完成后將列類型更改為數字。 它有效,但僅適用於 1 列:
df['1_month_int'] = df['1_month']
df['1_month_int'].replace("High",5, inplace=True)
df['1_month_int'].replace("Above Average",4, inplace=True)
df['1_month_int'].replace("Average",3, inplace=True)
df['1_month_int'].replace("Below Average",2, inplace=True)
df['1_month_int'].replace("Low",1, inplace=True)
df['1_month_int'] = pandas.to_numeric(df['1_month_int'])
我不能讓它同時為多個列工作:
df['1_month_int'] = df['1_month']
df['6_month_int'] = df['6_month']
df['12_month_int'] = df['12_month']
df[['3_month_int', '6_month_int', '12_month_int']/
.replace("High",5, inplace=True)
etc..
我確信有更好的方法。
我對 Pandas 非常陌生,並且正在努力學習如何思考和解決此類問題的學習曲線。
對於在 Pandas 中處理此類數據操作的最佳實踐,我將不勝感激。
Series.map
。import pandas as pd
df = pd.DataFrame({
'1_month':['High', 'Above Average'], '6_month':['Average','Below Average'], '12_month':['Low','Low']
})
map_ = {'High' : 5,'Above Average' : 4,'Average' : 3,'Below Average' : 2,'Low' : 1}
for c in df.columns:
df[c+'_int'] = df[c].map(lambda x: map_[x])
df
1_month 6_month 12_month 1_month_int 6_month_int 12_month_int
0 High Average Low 5 3 1
1 Above Average Below Average Low 4 2 1
您可以使用系列的 map function 到 map 的值到給定的數字,如下所示
import numpy as np
import pandas as pd
values = ["High",
"Above Average",
"Average",
"Below Average",
"Low", ]
mapper = {key: i+1 for i, key in enumerate(values[::-1])}
columns = "1_month,6_month,12_month".split(",")
df = pd.DataFrame(np.random.choice(values,(10,3)), columns=columns)
for col in columns:
df[f"{col}_int"] = df[col].map(mapper)
display(df)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.