0

I imported 2 file texts and I want to sum and append the results of both files like this

import pandas as pd
import numpy as np

X = pd.read_csv('C:\\Users\\ahmed\\Desktop\\line format.txt', sep="\t", header=None)
X2 = pd.read_csv('C:\\Users\\ahmed\\Desktop\\line format2.txt', sep="\t", header=None)

print('X is : ',X)
print('X2 is : ',X2)

Results are like this :

X is :         0
0  1 2 3
1  4 5 6

X2 is :            0
0   7  8  9
1  10 11 12
2  13 14 15

what I want to do is to append like this

 1  2  3
 4  5  6
 7  8  9
10 11 12
13 14 15

and to sum like this

 8 10 12
14 16 18

Any help would be appreciated. thank you

9
  • For the first part, pd.concat(). For the summation question, how are you arriving at those sums? Commented Jun 18, 2019 at 20:15
  • thank you sum by rows forget about the third line in the second file Commented Jun 18, 2019 at 20:17
  • what is that 0 after X is:.... Commented Jun 18, 2019 at 20:19
  • 1
    pd.concat((X,X2)).groupby(level=0).sum()? Commented Jun 18, 2019 at 20:20
  • @QuangHoang That's the first line of printing the dataframe. Commented Jun 18, 2019 at 20:21

1 Answer 1

1

If I understand correctly, you're aiming to add the same indexes from separate df's. Does this suit your needs? I don't understand index 2 in X2 though? Is it to be dropped if the same index doesn't exist in X?

import pandas as pd

X = ({
    'A' :    [1,4],
    'B' :    [2,5],
    'C' :    [3,6],
})

X = pd.DataFrame(data=X)

X2 = ({
    'A' :    [7,10,13],
    'B' :    [8,11,14],
    'C' :    [9,12,15],
})

X2 = pd.DataFrame(data=X2)

df_add = X.add(X2, fill_value=0)

print(df_add)

      A     B     C
0   8.0  10.0  12.0
1  14.0  16.0  18.0
2  13.0  14.0  15.0
Sign up to request clarification or add additional context in comments.

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.