简体   繁体   中英

In a python pandas DataFrame, how do you shift row indexes up to fill empty rows?

See title. Basically, how do you turn a dataframe that looks like A into one that looks like B:

A:

Index: Field:
01     a
02     b
03     c
05     d
06     e
08     f

B:

Index: Field:
01     a
02     b
03     c
04     d
05     e
06     f

So I want to preserve the data, but shift the indexes together. (specifically, I have this data, and I want to plot it with matplotlib, but I don't want there to be giant spaces in the data, so I want the data points to be pushed together. Is this the right way of doing this?)

I would just use reset_index() :

In [7]: df
Out[7]: 
  Field
1     a
2     b
3     c
5     d
6     e
8     f

[6 rows x 1 columns]

In [8]: df.reset_index(drop=True)
Out[8]: 
  Field
0     a
1     b
2     c
3     d
4     e
5     f

[6 rows x 1 columns]

The drop=True says not to try to insert the original index into the DataFrame.

Alternatively, you could try the use_index=False option in df.plot() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM