Specialized CSV processed python

Asked 2 years ago, Updated 2 years ago, 27 views

What python code should I write to make the original CSV the CSV I want to achieve?

Original CSV (assuming dataframe)

Column A Column B Column C
102030

CSV you want to achieve

US>Number of lines 1
Column A. Column B. Column C

Even though columns A, B, and C exist, column names and values called the number of rows are added on them.
(Not the original CSV file format)

python

2022-09-30 20:17

1 Answers

I think this article can be applied.
Add to CSV in Pandas

An interesting feature for storing data is the append mode with the parameter a, which you can use to add data to an existing CSV file.

pandas.DataFrame.to_csv

mode:str
Python write mode, default 'w'.

You can prepare two DataFrames like this, write each DataFrame separately, and put the second in append mode.

import pandas as pd

df1 = pd.DataFrame ([1]], columns = ['Number of Lines'])
df2 = pd.DataFrame ([10, 20, 30]], columns = ['Column A', 'Column B', 'Column C')

outfilename = 'combined.csv'

df1.to_csv(outfilename, index=False, encoding='utf8')
df2.to_csv(outfilename, mode='a', index=False, encoding='utf8')

Well, the first two lines could be just a two-line text file, not DataFrame.


2022-09-30 20:17

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.