Set Every Second Row's Index To One New Value
What is a simple and direct way to set the index of every second row of my dataframe to, say, ''? The method I used to use, df.loc[1::2, 'index'] = '' used to work but no longer do
Solution 1:
One way,
df = df.set_axis(pd.Index([index if i not in range(1, df.shape[0], 2) else''for i, index in enumerate(df.index)],
name=df.index.name))
print(df)
Output
foo
bar
0 0.302340
0.744609
2 0.489255
0.542356
4 0.072797
0.810690
6 0.738350
0.939177
8 0.827072
0.751731
We could also use DataFrame.Index.values
but we need remove RangeIndex
. So the cleanest way is DataFrame.rename
df = df.rename(index=dict.fromkeys(df.index[1::2],''))
Post a Comment for "Set Every Second Row's Index To One New Value"