我正在编写一个对pandas数据帧标签进行操作的函数,我希望有一个参数if axis==0:
to_sort = df.index
elif axis==1:
to_sort = df.columns
else:
raise AttributeError
来决定是对索引还是列进行操作。
所以我写了类似的东西:
df
其中labels
是pandas数据帧。
有更好的方法吗?
注意我不是要求进行代码审查,而是更具体地询问是否存在pandas属性(类似于df.labels[0] # index
df.labels[1] # columns
对我来说有意义),这允许我根据参数/获取索引或列索引要通过。
例如(代码不工作):
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
when (item?.itemId) {
R.id.action_crop -> {
val bitmap = capturedReceiptImageView.bitmap
val bitmapCropped = BitmapHelper.cropBitmap(bitmap, capturedReceiptImageView.getDimensions())
capturedReceiptImageView.setImageBitmap(bitmapCropped)
capturedReceiptImageView.invalidate()
bitmap.recycle()
}
R.id.action_rotate_left -> {
val bitmap = capturedReceiptImageView.bitmap
val bitmapRotated = BitmapHelper.rotateBitmap(bitmap, -90.0f)
capturedReceiptImageView.setImageBitmap(bitmapRotated)
capturedReceiptImageView.invalidate()
bitmap.recycle()
}
R.id.action_rotate_right -> {
val bitmap = capturedReceiptImageView.bitmap
val bitmapRotated = BitmapHelper.rotateBitmap(bitmap, 90.0f)
capturedReceiptImageView.setImageBitmap(bitmapRotated)
capturedReceiptImageView.invalidate()
bitmap.recycle()
}
R.id.action_increase_contrast -> {
val bitmap = capturedReceiptImageView.bitmap
val bitmapChangedContrast = BitmapHelper.changeBitmapContrast(bitmap, 1.10f)
capturedReceiptImageView.setImageBitmap(bitmapChangedContrast)
capturedReceiptImageView.invalidate()
bitmap.recycle()
}
R.id.action_decrease_contrast -> {
val bitmap = capturedReceiptImageView.bitmap
val bitmapChangedContrast = BitmapHelper.changeBitmapContrast(bitmap, 0.90f)
capturedReceiptImageView.setImageBitmap(bitmapChangedContrast)
capturedReceiptImageView.invalidate()
bitmap.recycle()
}
R.id.action_save -> {
val bitmap = capturedReceiptImageView.bitmap
BitmapHelper.saveBitmap(bitmap, capturedReceiptUri)
}
else -> { return false }
}
return true
}
答案 0 :(得分:0)
查看reindex文档示例,我意识到我可以这样做:
axis
= {' index',' columns'} getattr
获取相关标签:labels = getattr(df, axis)
向其他大熊猫开放特定解决方案。
如果我被迫使用axis={1, 0}
,那么@Bharath建议使用辅助函数是有意义的。
答案 1 :(得分:0)
简短回答:您可以使用iloc(axis=...)
文档:http://pandas.pydata.org/pandas-docs/stable/advanced.html
您还可以指定.loc的axis参数来解释传递的 单轴上的切片机。
(他们似乎在iloc
参数)
axis
df = pd.DataFrame({"A":['a1', 'a2'], "B":['b1', 'b2']})
print(df)
输出:
A B
0 a1 b1
1 a2 b2
print(df.iloc(axis=0)[0].index)
输出:
Index(['A', 'B'], dtype='object')
print(df.iloc(axis=1)[0].index)
输出:
RangeIndex(start=0, stop=2, step=1)