Rom*_*omB 4 python dataframe pandas
我遇到了一个奇怪的问题,其中 merge_first 方法导致存储为 bool 的值向上转换为 float64。例子:
In [1]: import pandas as pd
In [2]: df1 = pd.DataFrame({"a": [True]})
In [3]: df2 = pd.DataFrame({"b": ['test']})
In [4]: df2.combine_first(df1)
Out[4]:
a b
0 1.0 test
Run Code Online (Sandbox Code Playgroud)
这个问题已经在3年前的一篇文章中报告过:pandas DataFrame的combine_first和update方法有奇怪的行为。这个问题被告知要解决,但我在 pandas 0.18.1 下仍然有这种行为
感谢您的帮助
为了获得组合数据帧,必须在事件链的某个位置解决潜在的缺失值。我知道您的示例中没有遗漏任何内容。 None且np.nan不是int或bool。因此,为了拥有dtype包含 abool和 a Noneor 的公共部分np.nan,有必要将该列转换为objector float。作为“浮动”,大量操作变得更加高效,是一个不错的选择。显然,这并不是一直都是最好的选择,但仍然必须做出选择,并且 pandas 试图推断出最好的选择。
解决方法:
设置
df1 = pd.DataFrame({"a": [True]})
df2 = pd.DataFrame({"b": ['test']})
df3 = df2.combine_first(df1)
df3
Run Code Online (Sandbox Code Playgroud)
解决方案
dtypes = df1.dtypes.combine_first(df2.dtypes)
for k, v in dtypes.iteritems():
df3[k] = df3[k].astype(v)
df3
Run Code Online (Sandbox Code Playgroud)