-1

I am using pandas to load csv files containing questions/answers and assigning them to dict.

kids_csv_file = pd.read_csv(...) #columns Questions, SubQuestions, Answers

questions_dict = dict()

for i in ... :
_key = kids_csv_file.Questions[i] + '-' + kids_csv_file.SubQuestion[i]
questions_dict[_key] = kids_csv_file.Answers[i];

I am getting:

TypeError: must be str, not numpy.int64

David Leon
  • 1,017
  • 8
  • 25
sai
  • 75
  • 1
  • 3
  • 9
  • 2
    Welcome to StackOverflow. Please take the time to read this post on [how to provide a great pandas example](http://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples) as well as how to provide a [minimal, complete, and verifiable example](http://stackoverflow.com/help/mcve) and revise your question accordingly. These tips on [how to ask a good question](http://stackoverflow.com/help/how-to-ask) may also be useful. – jezrael Mar 05 '18 at 09:04

2 Answers2

0

Because kids_csv_file.Questions[i] + '-' + kids_csv_file.SubQuestion[i] is not a string. When you type kids_csv_file.Questions[i] + '-' + kids_csv_file.SubQuestion[i] python thinks, that string '-' must be joined with object kids_csv_file.Questions[i] and kids_csv_file.SubQuestion[i]

step 1) create string in separate line

step 2) append to dict your value

Nikolay Gogol
  • 819
  • 7
  • 6
0

as mentioned before, kids_csv_file.Questions[i] is not a string, so python can't use the string's Plus operator to concatenate it to other strings. you can use the format method, though:

questions_dict['{}-{}'.format(kids_csv_file.Questions[i], kids_csv_file.SubQuestion[i])] = kids_csv_file.Answers[i];

or better yet, create the index in a different line:

index = '{}-{}'.format(kids_csv_file.Questions[i], kids_csv_file.SubQuestion[i])
questions_dict[index] = kids_csv_file.Answers[i];
shayelk
  • 1,606
  • 1
  • 14
  • 32