pythonic
pythonic

Reputation: 33

Trying to write data to specific column using pandas dataframes

`

import pandas as pd
import numpy as np
import csv

header = ["Blues", "Jazz", "Rock", "Country", "Pop", "Rap", "Metal", "Classical"]

with open("music.csv", "w") as SectorCSV:
    csvwriter = csv.writer(SectorCSV, lineterminator = "\n")
    print("Creating Sector.csv")
    csvwriter.writerow(header)

df = ["Beethoven", "Mozart", "Adele", "Beyonce", "Nirvana", "Eminem", "Metallica", "Bach"]
df = pd.DataFrame(df)
df.to_csv("Sector.csv", index=False, columns=header, mode="a")

`

For example I want to append Beethoven into the classical column but I can't figure out how to append data to a specific column.

1 example of an error: KeyError: "None of [Index(['Blues', 'Jazz', 'Rock', 'Country', 'Pop', 'Rap', 'Metal', 'Classical'], dtype='object')] are in the [columns]"

Upvotes: 2

Views: 445

Answers (1)

Lokeshwar G
Lokeshwar G

Reputation: 146

I'm this is what you are excepting

df = pd.DataFrame()
df['columnname'] = ["Beethoven", "Mozart", "Adele", "Beyonce", "Nirvana", "Eminem", "Metallica", "Bach"]
df.to_csv("Sector.csv", index=False, columns=header, mode="a")

Upvotes: 1

Related Questions