Unable to add values to each column in a csv using pandas

Viewed 47

I have a csv which has the below content

AB22e,AD34f,GQ22c,BQ77b,GQ00p

Here it only contains headers. Now to each column, I want to add a value

So I have a dictionary where I have maintained a mapping between column names and values to add. It looks like this

col_map = {"AB22e": ["a", "v"], "AD34f": ["c", "w"], "GQ22c": ["p", "l"], "BQ77b": ["a", "d"], "GQ00p": ["oo", "c"]}

This is how I add values to columns and dump it back to the csv

import pandas as pd

columns = col_map.keys()
df2 = pd.read_csv('test.csv')

for column in columns:
    df2[column] = str(col_map[column]).encode('utf-8')

df2.to_csv('test.csv', index=False)

But nothing gets added to the csv. My final output should look like this

AB22e,AD34f,GQ22c,BQ77b,GQ00p
["a", "v"],["c", "w"],["p", "l"],["a", "d"],["oo", "c"]

What am I doing wrong?

2 Answers

You can use:

df.append(col_map, ignore_index=True).to_csv('test.csv', index=False)

Result:

   AB22e   AD34f   GQ22c   BQ77b    GQ00p
0  [a, v]  [c, w]  [p, l]  [a, d]  [oo, c]

you can may be create a dataframe from the available dictionary and reindex

pd.DataFrame({k:[v] for k,v in col_map.items()}).reindex(df2.columns,axis=1)

    AB22e   AD34f   GQ22c   BQ77b    GQ00p
0  [a, v]  [c, w]  [p, l]  [a, d]  [oo, c]
Related