![](/img/trans.png)
[英]How to create a data frame for each group in the pandas.groupby function?
[英]how to get the group names back by the ID after grouped by Pandas.groupby().ngroup()
我已按 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 ?
在計算之后我得到了 cityIDs 我想使用 python 將它們轉換回熊貓中的城市名稱。 使用城市 ID 填充
如果我理解正確,您想根據其他列檢索列值:
print(df.loc[df['cityID'] == 1, 'city'].iloc[0])
但是,如果您想要根據字典為列賦值:
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.