I have read data from csv file into a data frame consisting of more than 25000 rows and 15 columns and I need to move all rows (including the left-most -> index) one column to the right, so that I get an empty index and be able to fill it with integers. Names of columns, however, should stay at the same place. So, basically I need to move everything except column names one place to the right.
I tried to reindex it, but got an error:
ValueError: cannot reindex from a duplicate axis
Is there any way to do this?
Pandas Change Position of a Column (Last to the First) You can change the position of a pandas column in multiple ways, the simplest way would be to select the columns by positioning the last column in the first position. You can also use this approach to change the order of pandas columns in the desired order.
You need to create a new list of your columns in the desired order, then use df = df[cols] to rearrange the columns in this new order.
shift() If you want to shift your column or subtract the column value with the previous row value from the DataFrame, you can do it by using the shift() function. It consists of a scalar parameter called period, which is responsible for showing the number of shifts to be made over the desired axis.
reindex() to reorder columns in a DataFrame. Call pandas. DataFrame. reindex(columns=column_names) with a list of the column names in the desired order as column_names to reorder the columns.
In pandas you can only create a column to the right, unless you do join between two dataframe. Then you can re-arrange however you like.
import pandas as pd
df = pd.read_csv('data.csv', header=None, names = ['A','B','C'])
print(df)
A B C
0 1 2 3
1 4 5 6
2 7 8 9
3 10 11 12
df['D'] = pd.np.nan # this creates an empty series
# and appends to the right
print(df)
A B C D
0 1 2 3 NaN
1 4 5 6 NaN
2 7 8 9 NaN
3 10 11 12 NaN
df = df[['D','A','B','C']] # rearrange as you like
print(df)
D A B C
0 NaN 1 2 3
1 NaN 4 5 6
2 NaN 7 8 9
3 NaN 10 11 12
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With