用Pandas Dataframe中的新文本替换匹配的字符串

时间:2019-04-05 20:21:32

标签: python python-3.x pandas dataframe

我试图用通用ID替换“名称”列中的名称,并新建一个列“ research_code”,然后将删除“名称”列。

我不想删除重复项,但是我确实希望将“巴斯光年”的所有实例替换为相同的整数(即1)。因此,所有“嗡嗡声光年”都是“ 1”,所有“ Twighlight闪闪发光的”都是“ 2”。等

运行此命令时,我没有收到任何错误,但由于某些原因“ research_code”不存在。

  full_set = pd.read_csv(filename, index_col=None, header=0)

  grouped_set = full_set.groupby('Name')
  names = grouped_set.groups.keys()
  idx = 1
  for c in names:
    set_index = str(idx + 1)
    idx = int(set_index) + 1

    replaceables = full_set[(full_set.Name == str(c))]
    for index, row in replaceables.iterrows():

      print(row['Name'])
      print(row['research_code'])
      row['research_code'] = set_index
      print(row['research_code'])
  print(full_set.head)

1 个答案:

答案 0 :(得分:0)

可以使用类别。

import pandas as pd
import sys
if sys.version_info[0] < 3: 
    from StringIO import StringIO
else:
    from io import StringIO

filename = StringIO("""Name
Rahul
Doug
Joe
Buzzlightyear
Twighlight Sparkle
Twighlight Sparkle
Liu
""")

full_set = pd.read_csv(filename, index_col=None, header=0)
full_set['research_code']  = full_set['Name'].astype('category')
full_set['research_code'] = full_set['research_code'].cat.rename_categories([i for i in range(full_set['research_code'].nunique())])
print(full_set.drop(['Name'], axis=1))

列表理解的最后一点是没有根据的。只需通过提供rename_categories()新名称列表(上述问题中的符号)来重命名类别,该列表的名称与Names列中唯一值的数量一样长。

  research_code
0             4
1             1
2             2
3             0
4             5
5             5
6             3