0

I have a list consisting of several string as shown below list=['abc','cde','fgh'] I want to add all the values to a particular index of dataframe. I am trying it with the code

df1.ix[1,3]=[list]
df1.to_csv('test.csv', sep=',')

I want in dataframe at poistion 1,3 all values to be inserted as it is ['abc','cde','fgh']. I don't want to convert it to string or any other format. But it is giving me error. what I am doing wrong here

nishant kumar
  • 429
  • 7
  • 26
  • 1
    What is error? What is `df1.info()` ? – jezrael Oct 21 '16 at 12:05
  • the error is ----raise ValueError('Must have equal len keys and value ' ValueError: Must have equal len keys and value when setting with an ndarray – nishant kumar Oct 21 '16 at 12:07
  • Can you add sample of df1? Please check [How to make good reproducible pandas examples](http://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples) – jezrael Oct 21 '16 at 12:08

2 Answers2

3

I think you can use:

df1.ix[1,3] = L

Also is not recommended use variable list, because code word in python.

Sample:

df1 = pd.DataFrame({'a':[1,2,3], 'b':[1,2,3], 'c':[1,2,3], 'd':[1,2,3]})
print (df1)
   a  b  c  d
0  1  1  1  1
1  2  2  2  2
2  3  3  3  3

L = ['abc','cde','fgh'] 
df1.ix[1,3]= L

print (df1)
   a  b  c                d
0  1  1  1                1
1  2  2  2  [abc, cde, fgh]
2  3  3  3                3
jezrael
  • 729,927
  • 78
  • 1,141
  • 1,090
1

I think you meant to use 1:3 not 1,3

consider the pd.DataFrame df

df = pd.DataFrame(dict(A=list('xxxxxxx')))

use loc or ix
df.loc[1:3, 'A'] = ['abc', 'cde', 'fgh']
or
df.ix[1:3, 'A'] = ['abc', 'cde', 'fgh']
yields
enter image description here

piRSquared
  • 265,629
  • 48
  • 427
  • 571