S
S
Sergey Ilyin2020-06-18 04:17:04
Python
Sergey Ilyin, 2020-06-18 04:17:04

How to add a column with data from a list in pandas?

Hello.
There are two files:
1/ input_csv_file, which has a column ['index']
2/ input_file_w_address, which is a list of tuples: [(index1, address1), (index2, address2)], i.e. at [0] place is index, at [-1] -

address

text_input = open(input_file_w_address, 'r').read()
text_input = eval(text_input)
csv_input = pd.read_csv(input_csv_file)

then I want to:
1/ look at csv_input
2/ take every i-th value from the 'index' column
3/ take every y-th element in the list (it will be every tuple)
4/ look at the y[0]-element in it and compare with i
4/ if they are equal, take y[-1] and write it to a new column

for i in csv_input['index']:
    for i in range(csv_input.shape[0]):
        for y in text_input:
            text_input_index = y[0]
            text_input_address = y[-1]
            if i == text_input_index:
                csv_input['new_address'] = text_input_address


I could not get. tell me where is the mistake?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Ilyin, 2020-06-18
@sunsexsurf

everything turned out to be much simpler:

  1. We need to take a list of tuples
  2. Determine indexes and (in my case) addresses
  3. Use special pandas construct: df.loc

for y in text_input:
    text_input_index = y[0]
    text_input_address = y[-1]
    csv_input.loc[csv_input['index'] == int(text_input_index),
                  'new_address'] = text_input_address

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question