[英]Python: How to approach mapping a json object onto a dataframe int64 based id column
[英]Populate an int64 DataFrame column based on index of a list in Python
我有一个带有所有int64类型列的DataFrame。
City Val ...
0 3 1
1 2 43
2 0 32
3 1 54
然后,我列出了类别名称:
names = ['Sydney', 'Tokyo', 'Vancouver', 'Toronto']
我要基于names
列表索引(即0 ='Sydney'和1 ='Tokyo'),使用城市名称填充“城市”列。
理想的结果:
City Val ...
0 Toronto 1
1 Vancouver 43
2 Sydney 32
3 Tokyo 54
我试过了: df['City'].loc[df['City'].isin(names), df['City']]=names.index(df['City'])
,但是报错
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
并且,我想将“城市”列更改为类别类型。
df['City'] = df['City'].astype('category')
df['City'].cat.set_categories(names, ordered=True, inplace=True)
将Series.map
与enumerate
创建的字典一起使用:
names = ['Sydney', 'Tokyo', 'Vancouver', 'Toronto']
df['City'] = df['City'].map(dict(enumerate(names)))
print (df)
City Val
0 Toronto 1
1 Vancouver 43
2 Sydney 32
3 Tokyo 54
详细说明 :
print (dict(enumerate(names)))
{0: 'Sydney', 1: 'Tokyo', 2: 'Vancouver', 3: 'Toronto'}
然后对于分类:
df['City'] = pd.CategoricalIndex(df['City'].map(dict(enumerate(names))),
ordered=True,
categories=names)
要么:
df['City'] = (df['City'].map(dict(enumerate(names)))
.astype('category', ordered=True, categories=names))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.