两个数据框的按列串联
Column wise concatenation of two dataframes
我是 Python 和 Pandas 模块的初学者。我正在处理一个统计问题,我想在其中合并两个具有特定样式的数据框。
这是我的第一个平均值数据框:
- 5.006 3.418 1.464 0.244
- 5.936 2.770 4.260 1.326
- 6.588 2.974 5.552 2.026
然后是标准值的第二个数据帧:
- 0.352490 0.381024 0.173511 0.107210
- 0.516171 0.313798 0.469911 0.197753
- 0.635880 0.322497 0.551895 0.274650
那么有什么方法可以合并这两个数据帧,使最终输出看起来像 "mean"±"std" 吗?比如 "5.006 ± 0.352490"?
谢谢!
使用 .astype
转换为字符串,然后简单的连接就足够了。
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
如果您在两个数据框中具有相同的索引和列,则效果很好。如果没有,您可以将一个设置为另一个:
df2.index = df.index
df2.columns = df.columns
out = df.astype(str) + ' ± ' + df2.astype(str)
详情:
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
您需要连接两者 df
,需要相同的索引和列名称:
df1.astype(str) + ' ± ' + df2.astype(str)
另一个解决方案:
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
我是 Python 和 Pandas 模块的初学者。我正在处理一个统计问题,我想在其中合并两个具有特定样式的数据框。
这是我的第一个平均值数据框:
- 5.006 3.418 1.464 0.244
- 5.936 2.770 4.260 1.326
- 6.588 2.974 5.552 2.026
然后是标准值的第二个数据帧:
- 0.352490 0.381024 0.173511 0.107210
- 0.516171 0.313798 0.469911 0.197753
- 0.635880 0.322497 0.551895 0.274650
那么有什么方法可以合并这两个数据帧,使最终输出看起来像 "mean"±"std" 吗?比如 "5.006 ± 0.352490"?
谢谢!
使用 .astype
转换为字符串,然后简单的连接就足够了。
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
如果您在两个数据框中具有相同的索引和列,则效果很好。如果没有,您可以将一个设置为另一个:
df2.index = df.index
df2.columns = df.columns
out = df.astype(str) + ' ± ' + df2.astype(str)
详情:
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
您需要连接两者 df
,需要相同的索引和列名称:
df1.astype(str) + ' ± ' + df2.astype(str)
另一个解决方案:
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