Yujian
Yujian

Reputation: 169

Column wise concatenation of two dataframes

I'm a beginner in both Python and Pandas module. I'm working on a statistics problem in which I want to merge two dataframes with specific styles.

Here is my 1st dataframe for the mean values:

- 5.006 3.418   1.464   0.244
 - 5.936    2.770   4.260   1.326
 - 6.588    2.974   5.552   2.026

And then is the 2nd dataframe for the std values:

 - 0.352490 0.381024    0.173511    0.107210
 - 0.516171 0.313798    0.469911    0.197753
 - 0.635880 0.322497    0.551895    0.274650

So are there any ways to merge the two dataframes so the final output would look like "mean"±"std"? such as "5.006 ± 0.352490"?

Thank you!

Upvotes: 2

Views: 1320

Answers (2)

jezrael
jezrael

Reputation: 863611

You need concatenate both df, need same index and columns names:

df1.astype(str) + ' ± ' + df2.astype(str)

Another solution:

df1.astype(str).add(' ± ').add(df2.astype(str))

df = df1.astype(str) + ' ± ' + df2.astype(str)
print (df)
                    0                 1                 2                 3
0   -5.006 ± -0.35249  3.418 ± 0.381024  1.464 ± 0.173511   0.244 ± 0.10721
1  -5.936 ± -0.516171   2.77 ± 0.313798   4.26 ± 0.469911  1.326 ± 0.197753
2   -6.588 ± -0.63588  2.974 ± 0.322497  5.552 ± 0.551895   2.026 ± 0.27465

Upvotes: 1

cs95
cs95

Reputation: 403128

Convert to string using .astype and then a simple concatenation should suffice.

out = df.astype(str) + ' ± ' +  df2.astype(str)
print(out)
                  0                 1                 2                 3
0   5.006 ± 0.35249  3.418 ± 0.381024  1.464 ± 0.173511   0.244 ± 0.10721
1  5.936 ± 0.516171   2.77 ± 0.313798   4.26 ± 0.469911  1.326 ± 0.197753
2   6.588 ± 0.63588  2.974 ± 0.322497  5.552 ± 0.551895   2.026 ± 0.27465

Works nicely provided you have the same index and columns across both dataframes. If not, you can do set one to the other:

df2.index = df.index
df2.columns = df.columns
out = df.astype(str) + ' ± ' +  df2.astype(str)

Details:

df    
       0      1      2      3
0  5.006  3.418  1.464  0.244
1  5.936  2.770  4.260  1.326
2  6.588  2.974  5.552  2.026

df2    
          0         1         2         3
0  0.352490  0.381024  0.173511  0.107210
1  0.516171  0.313798  0.469911  0.197753
2  0.635880  0.322497  0.551895  0.274650

Upvotes: 3

Related Questions