添加 Multiindex Dataframe 和对应的 Series
Add Multiindex Dataframe and corresponding Series
我无法添加多索引数据框和相应的系列。例如,
df = pd.DataFrame({
'a': [0, 0, 1, 1], 'b': [0, 1, 0, 1],
'c': [1, 2, 3, 4], 'd':[1, 1, 1, 1]}).set_index(['a', 'b'])
# Dataframe might contain records that are not in the series and vice versa
s = df['d'].iloc[1:]
df + s
产生
ValueError: cannot join with no overlapping index names
有谁知道如何解决这个问题?我可以通过单独添加每一列来解决这个问题,例如使用
df['d'] + s
但我想在一次操作中添加这两个。非常感谢任何帮助。
默认情况下,+
尝试沿列对齐,以下内容适用于 +
:
s = df.iloc[:, 1:]
df + s
# c d
#a b
#0 0 NaN 2
# 1 NaN 2
#1 0 NaN 2
# 1 NaN 2
在您的情况下,您需要沿索引对齐。您可以使用 add
方法显式指定 axis=0
:
df.add(s, axis=0)
# c d
#a b
#0 0 NaN NaN
# 1 3.0 2.0
#1 0 4.0 2.0
# 1 5.0 2.0
我无法添加多索引数据框和相应的系列。例如,
df = pd.DataFrame({
'a': [0, 0, 1, 1], 'b': [0, 1, 0, 1],
'c': [1, 2, 3, 4], 'd':[1, 1, 1, 1]}).set_index(['a', 'b'])
# Dataframe might contain records that are not in the series and vice versa
s = df['d'].iloc[1:]
df + s
产生
ValueError: cannot join with no overlapping index names
有谁知道如何解决这个问题?我可以通过单独添加每一列来解决这个问题,例如使用
df['d'] + s
但我想在一次操作中添加这两个。非常感谢任何帮助。
默认情况下,+
尝试沿列对齐,以下内容适用于 +
:
s = df.iloc[:, 1:]
df + s
# c d
#a b
#0 0 NaN 2
# 1 NaN 2
#1 0 NaN 2
# 1 NaN 2
在您的情况下,您需要沿索引对齐。您可以使用 add
方法显式指定 axis=0
:
df.add(s, axis=0)
# c d
#a b
#0 0 NaN NaN
# 1 3.0 2.0
#1 0 4.0 2.0
# 1 5.0 2.0