pandas - Python pandas数据框,如何获取设置的数字
问题描述
这是示例:
df=pd.DataFrame([('apple'),('apple'),('apple'),('orange'),('orange')],columns=['A'])
df
Out[5]:
A
0 apple
1 apple
2 apple
3 orange
4 orange
我想在它旁边分配一个数字,例如,apple 是第一组列表 ['apple','orange'],B 列是 1,然后是 2 为橙色:
A B
0 apple 1
1 apple 1
2 apple 1
3 orange 2
4 orange 2
贝娄行不通。
df['B']=df['A'].tolist().index(df['A']) +1
解决方案
您可以使用该pd.factorize
功能。此函数用于将数组转换为分类数组。
pd.Series.factorize
也可以作为pd.Series
对象的方法使用:
codes, _ = df["A"].factorize()
df["B"] = codes + 1
print(df)
A B
0 apple 1
1 apple 1
2 apple 1
3 orange 2
4 orange 2
推荐阅读
- sql - WITH 子句:仅包括每个表中的某些值
- android - 我无法播放 m3u8 格式的视频
- laravel - 在创建时验证 laravel 中的重叠日期
- oracle-coherence - 连贯性错误我在 oracle 连贯性中遇到错误,例如“无法将类型 -28 转换为集合类型
- docker - 在 Docker 容器中访问 Redis CLI
- python - 使用 openpyxl 对 XLSX 工作簿中的选项卡进行排序
- google-translate - 谷歌翻译小部件是免费或付费功能 googleTranslateElementInit()
- r - 控制 R igraph 中节点和边的绘制顺序?
- amazon-web-services - VSTS AWS Elastic Beanstalk 部署问题
- matlab - 异数循环 Simulink 中的持久变量