python - 熊猫:按顺序将唯一值返回到列
问题描述
我不确定在这种情况下我应该如何进行。
考虑像下面这样的df,当我这样做时df.A.unique()
->给我一个这样的数组[1, 2, 3, 4]
但我也想要这个值的索引,比如numpy.unique()
df = pd.DataFrame({'A': [1,1,1,2,2,2,3,3,4], 'B':[9,8,7,6,5,4,3,2,1]})
df.A.unique()
>>> array([1, 2, 3, 4])
和
np.unique([1,1,1,2,2,2,3,3,4], return_inverse=True)
>>> (array([1, 2, 3, 4]), array([0, 0, 0, 1, 1, 1, 2, 2, 3]))
我怎样才能在熊猫中做到这一点?带索引的唯一值。
解决方案
在pandas
我们有drop_duplicates
df.A.drop_duplicates()
Out[22]:
0 1
3 2
6 3
8 4
Name: A, dtype: int64
匹配np.unique
输出factorize
pd.factorize(df.A)
Out[21]: (array([0, 0, 0, 1, 1, 1, 2, 2, 3]), Int64Index([1, 2, 3, 4], dtype='int64'))
推荐阅读
- javascript - Antd Upload的Dragger组件上传跨域发生
- highcharts - 如何将自定义多选添加到 highcharts 图例?
- ruby - 使用 Ruby Sequel 插入带有硬编码值的选择
- c - 使用单个 nChannel 将 IplImage 转换为 SDL_Surface
- dagger-2 - Android:创建bundle的新实例并在mvp的匕首中传递给意图
- css - 如何获得 sass 过滤器的结果颜色:在特定的十六进制颜色上饱和()?
- google-bigquery - 如果我的浏览器崩溃/计算机关闭,BigQuery 是否会使用目标表完成长时间运行的作业?
- php - Mailchimp API (PHP) - 您的广告系列尚未准备好发送
- java - 在java中计算数组中的重复次数
- xamarin - 在 Xamarin 表单中禁用连字