Home > Mobile >  join two dataframes after a specific column but showing no index
join two dataframes after a specific column but showing no index

Time:05-21

I am converting my date into matlab datenum and saving values in text file. then I am reading that csv and trying to add those values in existing dataframe after id column. I can direct add it at the end or as a 1st column but I can't add it after a specific column. number of rows are eual in both dataframes. it throws following error KeyError: 'datenum' Here is what i am doing

import pandas as pd
import datetime
import numpy as np
from datetime import datetime as dt
from datetime import timedelta
import os
df=pd.read_csv(r'C:\example.csv')
def datenum(d):
    return 366   d.toordinal()   (d - dt.fromordinal(d.toordinal())).total_seconds()/(24*60*60)

d = dt.strptime('2021-01-01 00:15:00','%Y-%m-%d %H:%M:%S')
column = df['date']
new_column = [dt.strptime(i,'%Y-%m-%d %H:%M:%S') for i in column]
end_column = [datenum(i) for i in new_column]
for i in end_column:
    print(i)
        df['Datetime'] = pd.to_datetime(df['date'])
df[ df['Datetime'].diff() > pd.Timedelta('15min') ]
    np.savetxt('timePminus.txt', end_column,fmt='% 1.5f')
    
    
    df['Datetime'] = pd.to_datetime(df['date'])
df[ df['Datetime'].diff() > pd.Timedelta('15min') ]

after that reading this csv

import pandas as pd
import datetime
import numpy as np
from datetime import datetime as dt
from datetime import timedelta
import os
df=pd.read_csv(r'example.csv')
df1=pd.read_csv(r'time.csv')
df2= pd.concat([df, df1], axis=1, join='outer')
print(df2)
df2= pd.concat([df, df1], axis=1, join='outer')
print(df2.get('datenum'))
df3=pd.DataFrame().assign(B=df2['B'],A=df2['A'],datenum=df2['datenum'],D=df2['D'])
print(df3)
it throws error keyerror:datenum here is the dataframe or csv

 A,B,C
    2021-01-02 00:15:00,"43289,95698800",236985
    2021-01-01 00:30:00,"425962,555555",236985
    2021-01-01 00:45:00,"2368,56980000",236985
    2021-01-01 01:00:00,"2368,56980000",236985
   2021-01-15 01:15:00,"2368,56980000",236985
   2021-05-01 01:30:00,"2368,56980000",236985

if I do print(df2.get('datenum')) output is none. 2nd dataframe

 datenum
 738157.01042
 738157.02083
 738157.03125
 738157.04167
 738157.05208
 738157.06250

can some one please guide me what is wrong. I am trying it for hours. Thanks in advance.

CodePudding user response:

If you are looking to just re-arrange your dataframe columns after concat you can do,

column_order = ['id', 'datenum', 'A', 'B', 'C']
df = df[column_order]
  • Related