So I am working on a code where I take values from the csv file and multiply them with some numbers but when I save and export the results the values from the imported file are also copied to the new file along with the results. I just want the results in the output file.
df = pd.read_csv('DAQ4.csv')
df['furnace_power'] = df['furnace_voltage']*df['furnace_current']*0.52 #calculating the furnace power
df['heat_pump_power'] = (df['pump_current']*230)*0.62
with open('DAQsol.csv', 'w', newline='') as f:
thewriter = csv.writer(f)
df.to_csv('DAQsol.csv')
This is not the full code but should be enough to understand. so basically I just want the heat pump power and the furnace power to appear in the output file not the whole pump current and voltage from the imported DAQ 4 file.
CodePudding user response:
Just make an empty dataframe and populate it with your new calculations:
df = pd.read_csv('DAQ4.csv')
df2 = pd.DataFrame()
df2['furnace_power'] = df['furnace_voltage']*df['furnace_current']*0.52 #calculating the furnace power
df2['heat_pump_power'] = (df['pump_current']*230)*0.62
df2.to_csv('DAQsol.csv')
CodePudding user response:
df['furnace_power'] = df['furnace_voltage']*df['furnace_current']*0.52 #calculating the furnace power
df['heat_pump_power'] = (df['pump_current']*230)*0.62
These two lines just modify the dataframe that you loaded. This means that all the other columns still exist, but just aren't modified. By calling df.to_csv('DAQsol.csv')
you are saving the whole dataframe, with the unwanted and unmodified columns.
One way to not export these columns to the output .csv
file, is to drop them out. This can be achieved with the following code:
df.drop(columns=['unwanted_column_1', 'unwanted_column_two'])
CodePudding user response:
Hi here you have an example reading and saving in a diferent file after some calculations:
from os import sep
import pandas as pd
#reading the csv file as dataframe
df= pd.read_csv('DAQ4.csv',delimiter=';',header=None)
df['furnace_power'] = df['furnace_power'].apply(lambda x: x*x*0.52)
df['heat_pump_power'] = df['furnace_power'].apply(lambda x: x*230*0.62)
#saving the dataframe as csv file
df.to_csv('out_file.csv', sep=';', index=False)
I hope it works for you.