-2

enter image description here

Hi, is there any way in Python for me to change the columns' positions like below: enter image description here

Thanks a lot!

Update: I have been trying to reframe the columns in the dump way, any code I can apply to increase the efficiency? Thanks.

now = dt.datetime.now()
length = relativedelta(weeks = 8)
start = now - length
end = now
stocks = ['TSLA','AMZN','FB']
tokens = ['BTC-USD','ETH-USD','DOGE-USD','XRP-USD']

#2. Get data and arrange them together without NaNs
stocks = web.DataReader(stocks, 'yahoo', start, end)
tokens = web.DataReader(tokens, 'yahoo', start, end)
df = tokens.merge(stocks, how='inner', right_index = True, left_index = True)
df.dropna(inplace = True)
df = df[[('Open', 'TSLA'),('High', 'TSLA'),('Low', 'TSLA'),('Close', 'TSLA'),('Adj Close', 'TSLA'),('Volume', 'TSLA'),
                          ('Open', 'AMZN'),('High', 'AMZN'),('Low', 'AMZN'),('Close', 'AMZN'),('Adj Close', 'AMZN'),('Volume', 'AMZN'),
                          ('Open', 'FB'),('High', 'FB'),('Low', 'FB'),('Close', 'FB'),('Adj Close', 'FB'),('Volume', 'FB'),
                          ('Open', 'BTC-USD'),('High', 'BTC-USD'),('Low', 'BTC-USD'),('Close', 'BTC-USD'),('Adj Close', 'BTC-USD'),('Volume', 'BTC-USD'),
                          ('Open', 'ETH-USD'),('High', 'ETH-USD'),('Low', 'ETH-USD'),('Close', 'ETH-USD'),('Adj Close', 'ETH-USD'),('Volume', 'ETH-USD'),
                          ('Open', 'DOGE-USD'),('High', 'DOGE-USD'),('Low', 'DOGE-USD'),('Close', 'DOGE-USD'),('Adj Close', 'DOGE-USD'),('Volume', 'DOGE-USD'),
                          ('Open', 'XRP-USD'),('High', 'XRP-USD'),('Low', 'XRP-USD'),('Close', 'XRP-USD'),('Adj Close', 'XRP-USD'),('Volume', 'XRP-USD')]]
df.to_csv('Data/newohlc.csv')
Ka Kin Li
  • 3
  • 2
  • you have used the pandas and dataframe tags but the screenshots you are showing are of excel. i assume you want to change your df column order which you are then outputting as a csv? have you checked this thread? https://stackoverflow.com/questions/13148429/how-to-change-the-order-of-dataframe-columns#:~:text=You%20need%20to%20create%20a,columns%20in%20this%20new%20order. – Scinana May 25 '21 at 11:19
  • @Scinana thanks, I find some hints from the thread – Ka Kin Li May 25 '21 at 15:45

2 Answers2

0

You can use the syntax DataFrame[["column1", "column2", "column3"]] with the column names in the desired order to reorder the columns. Example:

import pandas as pd
import numpy as np
df1 = {
    'Name':['George','Andrea','micheal','maggie','Ravi',
               'Xien','Jalpa'],
     'Gender':["M","F","M","F","M","M","F"],      
    'Score':[62.7,47.7,55.6,74.6,31.5,77.3,85.4],
    'Rounded_score':[63,48,56,75,32,77,85]
   }
df1 = pd.DataFrame(df1,columns=['Name','Gender','Score','Rounded_score'])
print(df1)
df2=df1.reindex(columns= ['Rounded_score', 'Gender', 'Score','Name'])
print(df2)

drauedo
  • 641
  • 4
  • 17
0

If you want to generate the list of tuples you are using to position/rename the columns you could use something like this.

Note, there's probably a better way than using a double loop and I did have something working using zip but when using that method I wasn't able to get the sorting right..

For example, all the open prices were grouped together rather than all the prices etc. being grouped by stock/token.


import datetime as dt
from dateutil.relativedelta import *
import pandas_datareader as web

now = dt.datetime.now()
length = relativedelta(weeks = 8)
start = now - length
end = now
stocks = ['TSLA','AMZN','FB']
tokens = ['BTC-USD','ETH-USD','DOGE-USD','XRP-USD']
cols = ['Open','High', 'Low', 'Close', 'Adj Close' , 'Volume']

newcols = []

for symbol in stocks+tokens:
  for col in cols:
    newcols.append((col, symbol))

print(newcols)

#2. Get data and arrange them together without NaNs
stock_data = web.DataReader(stocks, 'yahoo', start, end)
token_data = web.DataReader(tokens, 'yahoo', start, end)
df = token_data.merge(stock_data, how='inner', right_index = True, left_index = True)

print(df.head())

df.dropna(inplace = True)

df = df[newcols]

print(df.head())

I've found an alternative to using the double loop but I'm no sure it's 100% right.

I'll post it any way - need some fresh eyes to check it.


newcols = list(tuple(zip(cols*len(stocks+tokens), (stocks+tokens)*len(cols))))

newcols.sort(key = lambda x: (stocks+tokens).index(x[1])*10 + cols.index(x[0]))
norie
  • 9,609
  • 2
  • 11
  • 18