pandas DataFrame not merging but not giving an error

Viewed 312

I have a simple loop that adds the sentence number and the number + 1 and creates this into a DataFrame with named columns one and two. I am trying to merge the result of each iteration into the main DataFrame df but it doesn't seem to merge it, nor throw an error.

Here is the reproducible code:

df = pd.DataFrame()
for i in range(1, 6):
    sentence = pd.DataFrame((f'This is sentence {i}', i+1)).transpose()
    sentence.columns = ['one', 'two']
    print(sentence)
    if df.empty:
        df = sentence
        print('creating')
    else:
        df = df.merge(sentence, how='left', on=['one', 'two'])
        print('merging')

However the end result of df looks as such with only one row:

                  one two
0  This is sentence 1   2

Could someone explain to me why this isn't merging?

Thanks

EDIT

The final result should look as such:

                  one two
0  This is sentence 1   2
1  This is sentence 2   3
2  This is sentence 3   4
3  This is sentence 4   5
4  This is sentence 5   6

Is it something to do with the index both being 0 at time of merge?

4 Answers
for i in range(1, 6):
    sentence = pd.DataFrame([(f'This is sentence {i}', i+1)], columns=['one', 'two'])
    df = df.merge(sentence, how='outer')```
>>> df
                  one  two
0  This is sentence 1    2
1  This is sentence 2    3
2  This is sentence 3    4
3  This is sentence 4    5
4  This is sentence 5    6

Is df = df.append(sentence).reset_index(drop=True) maybe what you're looking for instead of merge?

Try this:

count = 5
sentence_list = [f'This is sentence {i}' for i in range(1,count+1)]
number_list = range(2,count+2)
df = pd.DataFrame({"one": sentence_list, "two": number_list})
print(df)

           one         two
0   This is sentence 1  2
1   This is sentence 2  3
2   This is sentence 3  4
3   This is sentence 4  5
4   This is sentence 5  6

Why not

df = df.append(sentence)
df.reset_index(drop=True, inplace=True)

instead of

df = df.merge(sentence, how='left', on=['one', 'two'])

Result :

                  one two
0  This is sentence 1   2
1  This is sentence 2   3
2  This is sentence 3   4
3  This is sentence 4   5
4  This is sentence 5   6

You can also use pandas.concat.

Related