xion
xion

Reputation: 89

How to delete first value in the last column of a pandas dataframe and then delete the remaining last row?

Below I am using pandas to read my csv file in the following format:

dataframe = pandas.read_csv("test.csv", header=None, usecols=range(2,62), skiprows=1)
dataset = dataframe.values

How can I delete the first value in the very last column in the dataframe and then delete the last row in the dataframe?

Any ideas?

Upvotes: 0

Views: 947

Answers (1)

Scott Boston
Scott Boston

Reputation: 153460

You can shift the last column up to get rid of the first value, then drop the last line.

df.assign(E=df.E.shift(-1)).drop(df.index[-1])

MVCE:

pd.np.random.seed = 123
df = pd.DataFrame(pd.np.random.randint(0,100,(10,5)),columns=list('ABCDE'))

Output:

    A   B   C   D   E
0  91  83  40  17  94
1  61   5  43  87  48
2   3  69  73  15  85
3  99  53  18  95  45
4  67  30  69  91  28
5  25  89  14  39  64
6  54  99  49  44  73
7  70  41  96  51  68
8  36   3  15  94  61
9  51   4  31  39   0

df.assign(E=df.E.shift(-1)).drop(df.index[-1]).astype(int)

Output:

    A   B   C   D   E
0  91  83  40  17  48
1  61   5  43  87  85
2   3  69  73  15  45
3  99  53  18  95  28
4  67  30  69  91  64
5  25  89  14  39  73
6  54  99  49  44  68
7  70  41  96  51  61
8  36   3  15  94   0

or in two steps:

df[df.columns[-1]] = df[df.columns[-1]].shift(-1)
df = df[:-1]

Upvotes: 2

Related Questions