我有一个Pandas多级索引数据框,需要从系列中为其中一列分配值。该系列与数据框的第一级索引共享其索引。
import pandas as pd
import numpy as np
idx0 = np.array(['bar', 'bar', 'bar', 'baz', 'foo', 'foo'])
idx1 = np.array(['one', 'two', 'three', 'one', 'one', 'two'])
df = pd.DataFrame(index = [idx0, idx1], columns = ['A', 'B'])
s = pd.Series([True, False, True],index = np.unique(idx0))
print df
print s
输出:
A B
bar one NaN NaN
two NaN NaN
three NaN NaN
baz one NaN NaN
foo one NaN NaN
two NaN NaN
bar True
baz False
foo True
dtype: bool
这些不起作用:
df.A = s # does not raise an error, but does nothing
df.loc[s.index,'A'] = s # raises an error
期望输出:
A B
bar one True NaN
two True NaN
three True NaN
baz one False NaN
foo one True NaN
two True NaN
.loc
分配值的语法应该是什么,希望有更好的pandas专家能够出现来回答这个问题。对我来说,这应该可以正常工作,因此必须有一种方法可以在不使用map
的情况下完成此操作。 - EdChumdf['A'] = pd.Series(df.index.get_level_values(0)).map(s).values
,这样更健壮,比你的示例更清晰。 - normanius