Search code examples
pythonpandasnansubtraction

Subtracting value from column gives NaN only


I have multiple column csv file and I want to subtract values of column X31-X27,Y31-Y27,Z31-Z27 from the same dataframe but when I am subtracting it gives me NaN values.
Here is the values of csv file:


It gives me the result as shown in picture


Help me to figure out this problem

import pandas as pd
import os
import numpy as np

df27 = pd.read_csv('D:27.txt', names=['No27','X27','Y27','Z27','Date27','Time27'], sep='\s+')
df28 = pd.read_csv('D:28.txt', names=['No28','X28','Y28','Z28','Date28','Time28'], sep='\s+')
df29 = pd.read_csv('D:29.txt', names=['No29','X29','Y29','Z29','Date29','Time29'], sep='\s+')
df30 = pd.read_csv('D:30.txt', names=['No30','X30','Y30','Z30','Date30','Time30'], sep='\s+')

df31 = pd.read_csv('D:31.txt', names=['No31','X31','Y31','Z31','Date31','Time31'], sep='\s+')

total=pd.concat([df27,df28,df29,df30,df31], axis=1)
total.to_csv('merge27-31.csv', index = False)
print(total)

df2731 = pd.read_csv('C:\\Users\\finalmerge27-31.csv')
df2731.reset_index(inplace=True)
print(df2731)

df227 = df2731[['X31', 'Y31', 'Z31']] - df2731[['X27', 'Y27', 'Z27']]
print(df227)

Solution

  • # input data
    df = pd.DataFrame({'x27':[-1458.88, 181.78, 1911.84, 3739.3, 5358.19], 'y27':[-5885.8, -5878.1,-5786.5,-5735.7, -5545.6], 
                       'z27':[1102,4139,4616,4108,1123], 'x31':[-1458, 181, 1911, np.nan, 5358], 'y31':[-5885, -5878, -5786, np.nan, -5554], 
                       'z31':[1102,4138,4616,np.nan,1123]})
    df
    
           x27     y27   z27     x31     y31     z31
    0 -1458.88 -5885.8  1102 -1458.0 -5885.0  1102.0
    1   181.78 -5878.1  4139   181.0 -5878.0  4138.0
    2  1911.84 -5786.5  4616  1911.0 -5786.0  4616.0
    3  3739.30 -5735.7  4108     NaN     NaN     NaN
    4  5358.19 -5545.6  1123  5358.0 -5554.0  1123.0
    
    
    
    
    pd.DataFrame(df1.values - df2.values).rename(columns={0:'x32-x27', 1:'y31-y27', 2:'z31-x31'})
    
    
    Out:
       x32-x27  y31-y27  z31-x31
    0    -0.88     -0.8      0.0
    1     0.78     -0.1      1.0
    2     0.84     -0.5      0.0
    3      NaN      NaN      NaN
    4     0.19      8.4      0.0