简体   繁体   English

Python - 更改重复的行名称

[英]Python - Changing names of rows if they are repeated

I wanna change the column "Cuenta" of my dataframe from the left one to the right table, like I show you in the next picture:我想将我的 dataframe 的“Cuenta”列从左侧更改为右侧表格,如下图所示:

entimaer image description here entimaer 图像描述在这里

As you can see the change depends of the number of repetitions of the value "Cuenta" over "Entidad".如您所见,变化取决于值“Cuenta”相对于“Entidad”的重复次数。

df = pd.DataFrame({
"Entidad":["A","A","A","A","A","A","A","B","B","B","B","B"],
"Cuenta": ["Surco","Lima","Miraflores","Lima","SMP","Surco","Lima","Surco","Lima","Miraflores","Lima","SMP"],
"Valor": [12,14,11,7,5,4,22,11,34,21,17,25],
})

Thank your again for your help.再次感谢您的帮助。

First create a new "suffix" column in your pandas dataframe:首先在你的pandas dataframe新建一个“后缀”栏:

df['suffix']=1

Then create a new column consisting of "Entidad" and "Cuenta":然后创建一个由“Entidad”和“Cuenta”组成的新列:

df['Entidad_Cuenta'] = df['Entidad']+'_'+df['Cuenta']

You can then groupby your dataframe by "Entidad_Cuenta" and compute the cumulative sum of the "suffix", in order to count the number of identical "Cuenta" values for each "Entidad";然后,您可以将 dataframe 按“Entidad_Cuenta”分组并计算“后缀”的累积和,以便计算每个“Entidad”的相同“Cuenta”值的数量; you may then append this suffix to "Cuenta":然后你可以 append 这个后缀到“Cuenta”:

df['Cuenta'] = df['Cuenta'] + df.groupby('Entidad_Cuenta').cumsum()['suffix'].astype(str)

df['Cuenta'] returns df['Cuenta']返回

0          Surco1
1           Lima1
2     Miraflores1
3           Lima2
4            SMP1
5          Surco2
6           Lima3
7          Surco1
8           Lima1
9     Miraflores1
10          Lima2
11           SMP1

I will leave it to you to figure out how to drop "suffix" and "Entidad_Cuenta" from your output dataframe.我将留给您弄清楚如何从您的 output dataframe 中删除“后缀”和“Entidad_Cuenta”。

store = {}

def fun(item):
  global store
  _ = store.setdefault(item, 0)
  store[item] += 1
  return str(item) + ('' if store[item] == 1 else str(store[item]))

# make sure to put store = {} before each column
df.Cuenta.apply(fun)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM