dataframe中的x_source、y_source、x_target、y_target填充

本文展示了如何使用Python的pandas库和numpy库对数据进行操作,包括创建DataFrame、应用元组转换、设置和更新数据值,以及在两个数据集之间进行匹配并更新特定列的值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import pandas as pd
import numpy as np

a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
d = [10, 21, 10, 21, 21, 10, 23, 23, 25, 25]
f = [0, 1, 1, 2, 0, 0, 2, 2, 0, 0]
df = pd.DataFrame({'gid': a, 'x': d, 'y': f})
#
print(df)

aa = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
bb = [10, 21, 10, 21, 21, 10, 23, 23, 25, 25]
cc = [0, 1, 1, 2, 0, 0, 2, 2, 0, 0]
dd = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
ee = [10, 21, 10, 21, 21, 10, 23, 23, 25, 25]
ff = [0, 1, 1, 2, 0, 0, 2, 2, 0, 0]
gg = [10, 21, 10, 21, 21, 10, 23, 23, 25, 25]

df_ = pd.DataFrame({'id': aa, 'source': bb, 'target': cc, 'x_source': dd, 'x_target': ee, 'y_source': ff, 'y_target': gg})
#
print(df_)

df['x_y'] = df[['x', 'y']].apply(tuple, axis=1)
print(df)
df_dict = df[['x_y', 'gid']].set_index('gid').to_dict()['x_y']
print(df)

for index, row in df_.iterrows():
    print(index, row['source'])
    if row['source'] in df_dict:
        df_.loc[df_['source'] == row['source'], 'x_source'] = df_dict[row['source']][0]
        df_.loc[df_['source'] == row['source'], 'y_source'] = df_dict[row['source']][1]

    if row['target'] in df_dict:
        df_.loc[df_['target'] == row['target'], 'x_target'] = df_dict[row['target']][0]
        df_.loc[df_['target'] == row['target'], 'y_target'] = df_dict[row['target']][1]

print(df_)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值