0

I wonder how to save a new pandas Series into a csv file in a different column. Suppose I have two csv files which both contains a column as a 'A'. I have done some mathematical function on them and then create a new variable as a 'B'.

For example:

data = pd.read_csv('filepath')

data['B'] = data['A']*10

# and add the value of data.B into a list as a B_list.append(data.B) 

This will continue until all of the rows of the first and second csv file has been reading.

I would like to save a column B in a new spread sheet from both csv files. For example I need this result:

colum1(from csv1)        colum2(from csv2)     
     data.B.value             data.b.value

By using this code:

pd.DataFrame(np.array(B_list)).T.to_csv('file.csv', index=False, header=None)

I won't get my preferred result.

0

2 Answers 2

4

Since each column in a pandas DataFrame is a pandas Series. Your B_list is actually a list of pandas Series which you can cast to DataFrame() constructor, then transpose (or as @jezrael shows a horizontal merge with pd.concat(..., axis=1))

finaldf = pd.DataFrame(B_list).T
finaldf.to_csv('output.csv', index=False, header=None)

And should csv have different rows, unequal series are filled with NANs at corresponding rows.

Sign up to request clarification or add additional context in comments.

1 Comment

I am new to python and pandas :) . Thanks guys for your help.
3

I think you need concat column from data1 with column from data2 first:

df = pd.concat(B_list, axis=1)
df.to_csv('file.csv', index=False, header=None)

4 Comments

Thanks for your response ,but I do not have data1 and data2 , data will be update in my loop till all the csv files are read.
data1 is name of Dataframe 1 and data2 second Dataframe.
I do not have 2 data frames as well. The original csv file will be updated by a new colum B and in the loop this column will be updated every time. I want to save this column in a new csv file before loosing the data.B.maybe I do not explain well what I mean.
Sorry, I dont understand it well. Now it should working perfectly.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.