使用Pandas替换列中的值时出错

时间:2018-09-15 23:23:38

标签: python pandas

我正在尝试用数字替换列中的值。这些是列中的唯一值:

public static void main(String[] args) {
    Scanner stdin = new Scanner(System.in);
    String choice;
    int age = 21;
    choice = stdin.nextLine();
    if (choice == "S" || choice == "T" || choice == "B" && age <= 21) {
    if (choice == "S")
        System.out.println("vegetable juice");
    else if (choice == "T")
        System.out.println("cranberry juice");
    else
        System.out.println("soda");         
}
    else if (choice == "S" || choice == "T" || choice == "B" && age > 21) {
    if (choice == "S")
        System.out.println("cabernet");
    else if (choice == "T")
        System.out.println("chardonnay");
    else
        System.out.println("IPA");  
}   
    else
System.out.println("invalid menu selection");
}

所以我做到了

['R2' '01' '02' 'C1']

但是当我尝试在假定的替换项后打印出df ['rates']时,我仍然得到相同的值:

data = pd.read_csv('file.csv')
df = pd.DataFrame(data)

df['rates'].apply({'R2': 1, '01' : 2, '02' : 3, 'C1' : 4}.get)

这是我的file.csv的样子

['R2' '01' '02' 'C1']

1 个答案:

答案 0 :(得分:1)

尝试amount,id,rates,height 1400,4,R2,3 1389,6,R2,8 10000,1,01,13

map

或者:

df['rates'].map({'R2': 1, '01' : 2, '02' : 3, 'C1' : 4},inplace=True)

实际上您的代码有效,但需要分配:

df['rates'] = df['rates'].map({'R2': 1, '01' : 2, '02' : 3, 'C1' : 4})
相关问题