pandas:将单元格值设置为当前行的索引?

时间:2018-06-14 13:17:28

标签: pandas

我有一个这样的数据框:

   a    b   c    country
0  5    7   11   Morocco
1  5    9   9    Nigeria
2  6    2   13   Spain

我想添加一行d,其中包含国家/地区名称加上行的索引(加1)。像这样:

   a    b   c    country    d
0  5    7   11   Morocco    1. Morocco
1  5    9   9    Nigeria    2. Nigeria
2  6    2   13   Spain      3. Spain

我该怎么做?我能做到:

df['d'] = '1. ' + df['country']

但是我很难弄清楚如何获得该行的索引。

1 个答案:

答案 0 :(得分:2)

将索引值转换为字符串并添加列public class User { [Key] public int IDUser { get; set; } [Required] public string Forename { get; set; } [Required] public string Name { get; set; } public string AvatarPath { get; set; } public string Email { get; set; } public string PhoneNumber { get; set; } public string Password { get; set; } public bool IsWebUser { get; set; } public DateTimeOffset CreatedAt { get; set; } public int? IDUser_CreatedBy { get; set; } public User User_CreatedBy { get; set; } public List<User> UsersAdded { get; set; } }

country

df['d'] = (df.index + 1).astype(str) + '. ' + df['country'] print (df) a b c country d 0 5 7 11 Morocco 1. Morocco 1 5 9 9 Nigeria 2. Nigeria 2 6 2 13 Spain 3. Spain 的另一种解决方案:

python 3.6+