python - 根据 Python 中列表的索引填充 int64 DataFrame 列

标签 python pandas

我有一个包含所有 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 列。

理想的结果:

       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))

关于python - 根据 Python 中列表的索引填充 int64 DataFrame 列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57089874/

相关文章:

python - 减少 Django 内存使用。低悬的果实?

python - python 中列表中的字典

python - 如何获取 Django ImageField 名称

python - iPython:使用 Pandas 计算单词数,如何计算最少出现的单词?

python - pandas 拆分行和列以相互匹配

python - 如何更新 Python Pandas DataFrame 中特定行中的值?

python - 如何快速将csv表导出到python字典?

python - 禁用编辑 QLineEdit

python - 从 Pandas Python 数据帧重新缩放到 (0,1) 某些列

python - 如何用 Pandas 划分两个不同形状的数据框?