gpt4 book ai didi

python - 映射数据帧不是系列 Pandas

转载 作者:太空宇宙 更新时间:2023-11-04 03:13:14 24 4
gpt4 key购买 nike

我是 pandas 的新手,我正在尝试映射多列而不是一列。 This page向我展示了如何使用 pd.Series 执行此操作,但我不知道如何映射多个

这是我的两个 DataFrames 我正在尝试 map

data2=pd.DataFrame(np.random.randn(5,2),index=range(0,5),columns=['x','y'])
data2['Cluster']=['A','B','A','B','C']
centers2=pd.DataFrame(np.random.randint(0,10,size=(3,2)),index= ['A','B','C'],columns=['x','y'])

这里 data2 看起来像:

data2

x y Cluster
0 0.151212 -0.168855 A
1 -0.078935 1.933378 B
2 -0.388903 0.444610 A
3 0.622089 1.609730 B
4 -0.346856 1.095834 C

centers2 看起来像:

centers2
x y
A 6 4
B 6 0
C 4 1

我希望在 data2 中创建两个单独的列,并使用适当的 center2 匹配。这是我的手动尝试

data2['Centers.x']=[6,6,6,6,4]
data2['Centers.y']=[4,0,4,0,1]
data2
x y Cluster Centers.x Centers.y
0 0.151212 -0.168855 A 6 4
1 -0.078935 1.933378 B 6 0
2 -0.388903 0.444610 A 6 4
3 0.622089 1.609730 B 6 0
4 -0.346856 1.095834 C 4 1

如何使用 map 函数执行此操作? (我知道如何使用循环来做到这一点,我需要一个矢量化解决方案。)

最佳答案

.merge() 最接近 pd.Series.map() for pd.DataFrame。您可以使用 suffixes=[] 关键字将自定义标题添加到重叠列,例如 suffices=['', '_centers']

注意 pd.Series 没有 .merge()pd.DataFrame 也没有 。 map ()

data2
x y Cluster
0 -1.406449 -0.244859 A
1 1.002103 0.214346 B
2 0.353894 0.353995 A
3 1.249199 -0.661904 B
4 0.623962 -1.754789 C

centers2
x y
A 0 9
B 6 9
C 0 6

你得到:

data2.merge(centers2, left_on='Cluster', right_index=True, suffixes=['', '_centers']).sort_index()

x y Cluster x_centers y_centers
0 -1.406449 -0.244859 A 0 9
1 1.002103 0.214346 B 6 9
2 0.353894 0.353995 A 0 9
3 1.249199 -0.661904 B 6 9
4 0.623962 -1.754789 C 0 6

还有 .join() 选项,这是访问 .merge()pd.concat() 的另一种方式> 如果 .merge() 对两个 DataFrame 都在 index 上 - 来自源:

def join(self, other, on=None, how='left', lsuffix='', rsuffix='',
sort=False):
return self._join_compat(other, on=on, how=how, lsuffix=lsuffix,
rsuffix=rsuffix, sort=sort)

def _join_compat(self, other, on=None, how='left', lsuffix='', rsuffix='',
sort=False):
from pandas.tools.merge import merge, concat

if isinstance(other, Series):
if other.name is None:
raise ValueError('Other Series must have a name')
other = DataFrame({other.name: other})

if isinstance(other, DataFrame):
return merge(self, other, left_on=on, how=how,
left_index=on is None, right_index=True,
suffixes=(lsuffix, rsuffix), sort=sort)
else:
if on is not None:
raise ValueError('Joining multiple DataFrames only supported'
' for joining on index')

关于python - 映射数据帧不是系列 Pandas ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37262315/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com