'Save to csv file with dataframe data obtained from for loop
I am trying to save data from a dataframe built during a while loop. However, on the exit of the loop, the LPCCfeatextr comes out empty. How can I parse the LPCCfeatextrdf dataframe to be saved to a csv file correctly?
Here is my code:
LPCCfeatextr = []
# Remove csv file if it exists
with contextlib.suppress(FileNotFoundError):
os.remove(filename2)
def extract_features(file_name):
try:
fs, sig = wavfile.read(file_name)
lpcs_feat = lpc(sig=sig, fs=fs, num_ceps=num_ceps)
File_name = file_name
shape = lpcs_feat.shape
pad_width = max_pad_len - lpcs_feat.shape[1]
lpcs_feat = np.pad(lpcs_feat, pad_width=((0, 0), (0, pad_width)), mode='constant')
LPCCfeatextr.append([File_name, shape, pad_width])
LPCCfeatextrdf = pd.DataFrame(LPCCfeatextr, columns=['File_name', 'Shape', 'Pad_width'])
df = pd.DataFrame(LPCCfeatextrdf)
except Exception as e:
print("Error encountered while parsing file: ", file_name)
return None
return lpcs_feat, LPCCfeatextrdf
# Convert into a Panda dataframe
LPCCfeatextrdf = pd.DataFrame(LPCCfeatextr, columns=['File_name', 'Shape', 'Pad_width'])
# dataframe from dictionary
df = pd.DataFrame(LPCCfeatextrdf)
df.to_csv(filename2, mode='a', index=False, header=True)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
