Reputation: 1046
I'm struggling to write list into a CSV file. So first of all i convert list to pandas dataframe and now truing to save it as columns to a file, but data is being displayed from new line. Can you please help me figure out what I've missing in my code
lst = ['Name', 'Age', 'City']
df = pd.DataFrame(lst)
df.to_csv('file.csv', mode='a', index=False, header=False)
Expected result: Name, Age, City
Upvotes: 1
Views: 7765
Reputation: 78690
If I understand correctly, you'd just have to add a .T
to your line to write the transposed dataframe.
df.T.to_csv('file.csv', mode='a', index=False, header=False)
---^
although if you are using pandas only to write lists as rows to csv files, you'd better have a look at the csv
module, because creating intermediary dataframes is pretty pointless.
import csv
lst = ['Name', 'Age', 'City']
with open('file.csv', 'a') as f:
csv.writer(f).writerow(lst)
Upvotes: 1
Reputation: 164673
To save as columns, assign your list as columns:
lst = ['Name', 'Age', 'City']
df = pd.DataFrame(columns=lst)
df.to_csv('file.csv', mode='a', index=False)
If not specified, the first argument to pd.DataFrame
is data
, so you must assign to columns
explicitly.
Upvotes: 3