ryan9025
ryan9025

Reputation: 269

Python: Write a list to a column in Pandas

I have two lists that both contain values that I want to write into a csv file. So the first thing I did is to import my csv file to pandas dataframe. Then I want to write two new columns and add those two lists to the new columns. My code is as below. Please note that the original csv file already has a few columns existed.

import pandas as pd

df = pd.read_csv('1.csv')  ## 1.csv is the csv file I want to import. 


a = [0.001, 5, 38, 70, 101, 140, 190]

b= [35, 65,  100, 160, 170, 200]

df['Start Time'] = a
df['End Time'] = b 

df.to_csv('1.csv')

However, when I run this code, it gave me an error as below,

ValueError: Length of values does not match length of index

If anyone knows how to solve this, please let me know. Appreciated!!

Upvotes: 3

Views: 10808

Answers (2)

Tints
Tints

Reputation: 21

Well you can also try out changing the datatypes of a and b into strings. In that way the NAN values will be left blank.

import pandas as pd

df = pd.read_csv('1.csv')  ## 1.csv is the csv file I want to import. 


a = [0.001, 5, 38, 70, 101, 140, 190]

b = [35, 65,  100, 160, 170, 200]

df['Start Time'] = str(a)
df['End Time'] = str(b) 

df.to_csv('1.csv')

Upvotes: 0

jezrael
jezrael

Reputation: 862641

I think you need create Series first, but get NaNs for all last values in df if length is not same as length of DataFrame:

df['Start Time'] = pd.Series(a, index = df.index[:len(a)])
df['End Time'] = pd.Series(b, index = df.index[:len(b)]) 

Sample:

df = pd.DataFrame({'a':range(10)})

a = [0.001, 9, 46, 84, 122, 153, 198]
b= [39, 76,  114, 150, 158, 210]

df['Start Time'] = pd.Series(a, index = df.index[:len(a)])
df['End Time'] = pd.Series(b, index = df.index[:len(b)]) 
print (df)
   a  Start Time  End Time
0  0       0.001      39.0
1  1       9.000      76.0
2  2      46.000     114.0
3  3      84.000     150.0
4  4     122.000     158.0
5  5     153.000     210.0
6  6     198.000       NaN
7  7         NaN       NaN
8  8         NaN       NaN
9  9         NaN       NaN

Upvotes: 4

Related Questions