0

I have tried the following code:

import pandas as pd
list1 = {'Names':[1,2,3,4,5]}

df = pd.DataFrame(list1)
df_csv = pd.read_csv('try.csv')
df_csv['Names'] = list1
df_csv.to_csv('try.csv', index=False, mode= 'a')

The error is as following:

"ValueError: Length of values does not match length of index"

I understand that the size of the dataframe doesn't match but how can I solve that?

So, this is what I want in try.csv file after appending: try.csv file

9
  • 1
    So what is your expected out put ....? Commented Apr 15, 2018 at 17:17
  • do: df_csv['Names'] = list1['Names'] Commented Apr 15, 2018 at 17:32
  • You can try: df_csv['Names'] = pd.DataFrame(list1) instead of df_csv['Names'] = list1 Commented Apr 15, 2018 at 17:52
  • @Wen I already have one column in the try.csv file and I would like to add another one with the data from 'list1'. The number of elements in both the columns are same. Commented Apr 16, 2018 at 6:17
  • @YOLO I get the same error again Commented Apr 16, 2018 at 7:33

3 Answers 3

1

From your code, the correct would be:

import pandas as pd
list1 = {'Names':[1,2,3,4,5]}

df = pd.DataFrame(list1)
df_csv = pd.read_csv('try.csv')
df_csv['Names'] = df.Names  # changed here
df_csv.to_csv('try.csv', index=False, mode= 'w')
Sign up to request clarification or add additional context in comments.

1 Comment

I get this error: " Error tokenizing data. C error: Expected 1 fields in line 7, saw 2"
0

You are trying to assign a dictionary here, whereas your row requires a list of values. You should try this:

import pandas as pd
list1 = {'Names':[1,2,3,4,5]}

df = pd.DataFrame(list1)
df_csv = pd.read_csv('try.csv')
df_csv['Names'] = list1['Names']
df_csv.to_csv('try.csv', index=False, mode= 'a')

Also, it is not clear why would you need an additional df DataFrame for this?

Comments

0

You can try using concat. Suppose your df_csv has more rows as below then, you can create new dataframe with list1 and concatenate as new column:

import pandas as pd
list1 = {'Names':[1,2,3,4,5]}

# creating dataframe with initial value instead of pd.read_csv
df_csv = pd.DataFrame({'col_1': [100,200,300,400,500,600,700]})
print(df_csv)

Result:

   col_1
0    100
1    200
2    300
3    400
4    500
5    600
6    700

Now, concatenate to df_csv with axis=1 by creating new dataframe with list1:

list1_df = pd.DataFrame(list1)
# concatenate df_csv and dataframe with list1_df
df_csv = pd.concat([df_csv,list1_df], axis=1)
print(df_csv)

Result:

   col_1  Names
0    100    1.0
1    200    2.0
2    300    3.0
3    400    4.0
4    500    5.0
5    600    NaN
6    700    NaN

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.