问题
Consider the following
In [214]: df = pd.DataFrame(index=range(4,8), data=[33,22,11,00])
In [215]: df
Out[215]:
0
4 33
5 22
6 11
7 0
I'd like to reverse the order of the first column, but maintain the index in its current order, so df
will look like
4 0
5 11
6 22
7 33
I can't seem to find the right reset_index
, reindex
, etc to make this happen.
回答1:
use iloc
and slice appropriately
df.iloc[::-1]
0
7 0
6 11
5 22
4 33
In order to preserve the index
use iloc
df.iloc[:] = df.iloc[::-1].values
use numpy
pd.DataFrame(df.values[::-1], df.index, df.columns)
Both yield
0
4 33
5 22
6 11
7 0
回答2:
You can also set your index into a temporary variable and then reapply index.
df = pd.DataFrame(index=range(4,8), data=[33,22,11,00])
idx=df.index.values
df.sort_values([0],inplace=True)
df.index=idx
Not as clever but easy to understand
来源:https://stackoverflow.com/questions/41774766/reverse-dataframe-column-but-maintain-the-index