Home > Software design >  How to solve the following errors "Name 'X' is not defined" when Subtracting mul
How to solve the following errors "Name 'X' is not defined" when Subtracting mul

Time:09-19

I want to subtract multiple column data from two text file. The text file contain 6 columns and these columns are not named.So I named it as No,X,Y,Z,Date,Time and seperated with comma. I want to perform X-X1, Y-Y1, Z-Z1. Date and Time are not important and they are only for reference. For this I have opened the files with different dataframe and I have used concat and then I produced another csv file which contains data from two text file in single CSV file. Now when I am subtracting the columns X-X1, Y-Y1, Z-Z1 I am getting the following error: "Name 'X' is not defined" also I am getting the following error: AttributeError: 'tuple' object has no attribute 'to_csv', when trying to produce file named "difference.csv". Please help me to solve this error. Below is my code.

import pandas as pd
import os
import numpy as np

df1 = pd.read_csv('D:\\Work\\Data1.txt', names=['No1','X1','Y1','Z1','Date1','Time1'], sep='\s ')
df2 = pd.read_csv('D:\\Work\\Data19.txt', names=['No','X','Y','Z','Date','Time'], sep='\s ')

total=pd.concat([df1,df2], axis=1)
total.to_csv("merge.csv")
cols = ['X','Y','Z','X1','Y1','Z1']
print(total)

df3 = pd.read_csv('C:\\Users\\Admin\\PycharmProjects\\project1\\merge.csv')

df4[X,Y,Z] = df3[X,Y,Z]-df3[X1,Y1,Z1]
print(df4)
df4.to_csv("difference.csv")

CodePudding user response:

How about fixing your code like this?

df1 = pd.read_table('D:\\Work\\Data1.txt', names=['No1','X1','Y1','Z1','Date1','Time1'], sep='\s ')

df2 = pd.read_table('D:\\Work\\Data19.txt', names=['No','X','Y','Z','Date','Time'], sep='\s ')

total.to_csv('merge.zip', index = False)

Also, I think the index of the data frame resulting from the code below is

total=pd.concat([df1,df2], axis=1) ['No1','X1','Y1','Z1','Date1','Time1','No','X','Y','Z','Date','Time']

I hope my answer is helpful

CodePudding user response:

try this

df3["X2"] = df3["X"]-df3["X1"]
df3["Y2"] = df3["Y"]-df3["Y1"]
df3["Z2"] = df3["Z"]-df3["Z1"]

df4 = df3.loc[:, ["X2", "Y2", "Z2"]
df4 = df4.rename(columns={"X2": "X", "Y2": "Y", "Z2": "Z"}) #optional

df4.to_csv("difference.csv")

  • Related