I think it is strange that .set_axis() can't accept index=/columns= kwargs, even though similar methods .rename(), .rename_axis(), .drop() and etc. can.
Personally, I think it would be more readable than specifying it with 0 or 1.
One trivial advantage is that it allows us to change rows and columns at once.
expect:
>>> df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]})
>>> df.set_axis(index=['a', 'b', 'c'])
A B
a 1 4
b 2 5
c 3 6
>>> df.set_axis(columns=['I', 'II'])
I II
0 1 4
1 2 5
2 3 6
>>> df.set_axis(index=['a', 'b', 'c'], columns=['I', 'II'])
I II
a 1 4
b 2 5
c 3 6
Comment From: rhshadrach
+1 for the API consistency here.
Comment From: leonarduschen
take
Comment From: leonarduschen
How should this work with Series?
Consideration:
- DataFrame.rename signature:
python
def rename(
self,
mapper: Renamer | None = None,
*,
index: Renamer | None = None,
columns: Renamer | None = None,
axis: Axis | None = None,
copy: bool = True,
inplace: bool = False,
level: Level | None = None,
errors: IgnoreRaise = "ignore",
) -> DataFrame | None:
- Series.rename signature:
python
def rename(
self,
index: Renamer | Hashable | None = None,
*,
axis: Axis | None = None,
copy: bool = True,
inplace: bool = False,
level: Level | None = None,
errors: IgnoreRaise = "ignore",
) -> Series | None:
Series.rename accepts all signature of DataFrame.rename except for mapper and columns (documentation is wrong, already reported at #46889)
Currently, we have DataFrame.set_axis and Series.set_axis current signature:
def set_axis(self, labels, axis: Axis = 0, inplace: bool = False):
We'll add index and columns to DataFrame.set_axis:
def set_axis(self, labels, index, columns, axis: Axis = 0, inplace: bool = False):
I think we shouldn't make any change to Series.set_axis. It still wouldn't be 100% consistent with .rename since Series.rename accepts index instead of mapper, but I don't think there's any way around it.
Comment From: rhshadrach
Agreed on not changing Series.set_axis (similar to how Series.rename doesn't have columns). I may be misunderstanding, but I don't think there should be consistency with mapper for Series.rename; supplying a mapper to Series.rename doesn't make sense.
Comment From: jbrockmendel
I think its a good thing that set_axis has One Obvious Way to be called, and a bad thing that other methods have multiple valid ways to do the same thing. -1 on changing here.
Comment From: rhshadrach
Personally, I think it would be more readable than specifying it with
0or1.
As the documentation states, one can also use 'index' and 'columns'. I think that takes care of the readability argument. The only other argument I see is being able to set both in a single rather than two calls, which I personally find negligible. Agree with @jbrockmendel we should prefer simplicity here. Closing.