假设我有一个带有键:数组的字典,例如:
In[0]: arrs = {
...: 'a': np.array([1, 2, 3]),
...: 'b': np.array([4, 5, 6])
}
还有一个 pandas DataFrame,其索引包含这些键:
In[1]: df = pd.DataFrame(index=list('abc'), columns = list('def'))
...: df
Out[1]:
d e f
a NaN NaN NaN
b NaN NaN NaN
c NaN NaN Na
我想用数组字典中的值填充 DataFrame。
这有效:
In[2]: for idx in ['a', 'b']:
...: df.loc[idx, :] = arrs[idx]
...: df
Out[2]:
d e f
a 1 2 3
b 4 5 6
c NaN NaN NaN
这很好,但我想向量化该操作。我尝试了我认为可行的方法:
In[3]: df.loc[('a', 'b'), :] = df.loc[('a', 'b'), :].index.map(lambda x: arrs[x])
但这会导致ValueError
:
ValueError: could not broadcast input array from shape (2) into shape (2,3)
为什么我的映射只计算数组的数量,而没有实际看到数组的形状?
最佳答案
在字典上使用DataFrame
构造函数,然后更新
第一个DataFrame
。
import pandas as pd
df.update(pd.DataFrame.from_dict(arrs, orient='index', columns=['d', 'e', 'f']))
输出:df
d e f
a 1 2 3
b 4 5 6
c NaN NaN NaN
关于python - 将 numpy 数组映射到 pandas DataFrame 会导致 ValueError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53145133/