Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/oracle/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何用Python中列表中的值替换面板数据中列中的值?_Python_Pandas - Fatal编程技术网

如何用Python中列表中的值替换面板数据中列中的值?

如何用Python中列表中的值替换面板数据中列中的值?,python,pandas,Python,Pandas,我有一个面板数据形式的数据库: Date id variable1 variable2 2015 1 10 200 2016 1 17 300 2017 1 8 400 2018 1 11 500 2015 2 12 150 2016 2 19 350 2017 2 15 250 2018 2 9 450 2015 3

我有一个面板数据形式的数据库:

Date id variable1 variable2
2015 1    10         200
2016 1    17         300
2017 1     8         400
2018 1    11         500
2015 2    12         150
2016 2    19         350
2017 2    15         250
2018 2     9         450
2015 3    20         100
2016 3     8         220
2017 3    12         310
2018 3    14         350
我有一个带有ID标签的列表

List = ['Argentina', 'Brazil','Chile']
我想用列表中的标签替换id的值

提前谢谢

Date id         variable1 variable2
2015 Argentina    10         200
2016 Argentina    17         300
2017 Argentina     8         400
2018 Argentina    11         500
2015 Brazil       12         150
2016 Brazil       19         350
2017 Brazil       15         250
2018 Brazil        9         450
2015 Chile        20         100
2016 Chile         8         220
2017 Chile        12         310
2018 Chile        14         350
试一试

df['id']=df['id'].map({1:'阿根廷',2:'巴西',3:'智利'})


df['id']=df['id'].map({k+1:v代表k,v在枚举(列表)})
map
是一种方法,使用
enumerate

d = {k:v for k,v in enumerate(List, start=1)}
df['id'] = df['id'].map(d)
输出:

    Date         id  variable1  variable2
0   2015  Argentina         10        200
1   2016  Argentina         17        300
2   2017  Argentina          8        400
3   2018  Argentina         11        500
4   2015     Brazil         12        150
5   2016     Brazil         19        350
6   2017     Brazil         15        250
7   2018     Brazil          9        450
8   2015      Chile         20        100
9   2016      Chile          8        220
10  2017      Chile         12        310
11  2018      Chile         14        350

嗨,凯南,谢谢你的评论,但对我来说仍然不起作用。请查看我的图片()。确保您的df['id']是dtype
int
对我有效。转换为数字df['id']。谢谢你,亲爱的广。