pandas 数据框合并 [英] Pandas dataframe merge
问题描述
我有一个来自 4 个数据帧的串联 Pandas 数据帧,如下所示:
在[121]中:所有出[121]:恩斯102P Y NaN NaN NaN103R Y NaN NaN NaN102P NaN NaN Y NaN103R NaN NaN Y NaN109F NaN NaN Y NaN103R NaN Y NaN NaN109F NaN Y NaN NaN102P NaN NaN NaN Y103R NaN NaN NaN Y109F NaN NaN NaN Y
我想将其合并为这样的数据帧:
E H N S102P Y NAN Y Y103R Y Y Y Y109F NAN Y Y Y
如何根据 all.index 合并它们?
对索引执行 groupby
(我从您发布的数据中推测值 102P...
代码>在索引中).并计算值.这将返回一个带有零和一的 DataFrame.只需用适当的值替换它们即可.
如果您有重复,则只需将条件从 ndf[ndf == 1]
更改为 ndf[ndf >0]
.
但是为什么要连接数据框而不是组合它们?示例:
<预><代码>>>>df1恩斯0102P Y NaN NaN NaN103R Y NaN NaN NaN>>>df2恩斯0102P NaN NaN Y NaN103R NaN NaN Y NaN109F NaN NaN Y NaN...>>>减少(拉姆达第一,第二:first.combine_first(第二),[df1, df2, df3, df4], pd.DataFrame())恩斯0102P Y 南 Y Y103R Y Y Y Y第 109 章I have a concatenated pandas dataframe from 4 dataframes like this:
In [121]: all
Out[121]:
E H N S
102P Y NaN NaN NaN
103R Y NaN NaN NaN
102P NaN NaN Y NaN
103R NaN NaN Y NaN
109F NaN NaN Y NaN
103R NaN Y NaN NaN
109F NaN Y NaN NaN
102P NaN NaN NaN Y
103R NaN NaN NaN Y
109F NaN NaN NaN Y
I want to consolidate this into a dataframe like this:
E H N S
102P Y NAN Y Y
103R Y Y Y Y
109F NAN Y Y Y
How can I merge them based on all.index?
Do a groupby
on the index (I presume from the data you posted that the values 102P...
are in the index). And count the values. That will return a DataFrame with zeros and ones. Just replace them with appropriate values.
>>> ndf = df.groupby(level=0).count()
>>> ndf[ndf == 1] = 'Y'
>>> ndf[ndf == 0] = np.nan
>>> ndf
E H N S
label
102P Y NaN Y Y
103R Y Y Y Y
109F NaN Y Y Y
If you have repetitions then just change the condition from ndf[ndf == 1]
to ndf[ndf > 0]
.
But why are you concatenating the data frames instead of combining them? Example:
>>> df1
E H N S
0
102P Y NaN NaN NaN
103R Y NaN NaN NaN
>>> df2
E H N S
0
102P NaN NaN Y NaN
103R NaN NaN Y NaN
109F NaN NaN Y NaN
...
>>> reduce(lambda first, second: first.combine_first(second),
[df1, df2, df3, df4], pd.DataFrame())
E H N S
0
102P Y NaN Y Y
103R Y Y Y Y
109F NaN Y Y Y
这篇关于 pandas 数据框合并的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!