简体   繁体   English

Pandas.groupby().ngroup()分组后如何通过ID取回组名

[英]how to get the group names back by the ID after grouped by Pandas.groupby().ngroup()

I have grouped my data in pandas by ID我已按 ID 在 Pandas 中对我的数据进行分组


df['cityID']=df.groupby(['city']).ngroup()

df =
    names    city       cityID
    ali     Islamabad      0
    john    lahore         1
    aslam   Islamabad      0
    khan    Peshawar       2
    umair   lahore         1

df2 =

    cityID    city
      2        ?
      1        ?
      2        ?
      2        ?
      0        ?
      1        ?
      1        ?
      2        ?
      1        ?
      0        ?
      2        ?
      0        ?



after come calculations I got cityIDs I want to convert them back to city names in pandas using python.在计算之后我得到了 cityIDs 我想使用 python 将它们转换回熊猫中的城市名称。 populating using the cityIDs使用城市 ID 填充

If I understood correct, you want to retrieve a column value based on other column:如果我理解正确,您想根据其他列检索列值:

print(df.loc[df['cityID'] == 1, 'city'].iloc[0])

But if what you want is to assign a value to a column depending on a dictionary:但是,如果您想要根据字典为列赋值:

d = {0: 'Islamabad', 1: 'lahore', 2: 'Peshawar'}
df["New_col"] = df["cityID"].apply(lambda x: d.get(x))

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

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