futui 发表于 2023-4-16 22:31:56

想通过另一个数据帧的值,增加本帧新增列的值,求帮忙,谢谢

data =[["2022-12-21","1.0440","-0.40","-0.40"],["2022-12-20","2.1016","-0.72","-0.77"],["2022-12-19","2.0891","-0.72","-0.77"],
["2022-12-18","1.9733","-0.77","-3.29"],["2022-12-17","0.7071","-1.64","-1.46"],
["2022-12-16","0.6967","-1.62","-1.46"],["2022-12-12","1.0440","-0.40","-0.40"]]
columns = ["日期","数值2","数值6","数值88"]
df=pd.DataFrame(data,columns =columns)
df


data =[["2022-12-20","8","6"],["2022-12-18","56","3"],["2022-12-12","8","7"],
["2022-12-16","5","8"]]
columns = ["日期","A","B"]
df2=pd.DataFrame(data,columns =columns)
df2


有以上两个数据帧,我想在dF2数据帧中,增加一列“C”,其值为:
df2日期 到df中的日期列去查找,找到(如果没找到,则为空),则为df对应行的“数值2”列的数值乘上1.5,再加上本df2中对应行A列的值,具体实例:

df2第一行日期为;"2022-12-20" ,在df中存在,且为第二行,那么df2["C"] = df["数值2"]*1.5+df2["A"],。。。。。依此类推
求大师帮忙,谢谢

isdkz 发表于 2023-4-16 22:34:03

可以使用 pandas 的 merge 函数将两个数据帧按照日期列合并,然后计算新列 "C"。以下是具体的代码:

import pandas as pd

data = [["2022-12-21","1.0440","-0.40","-0.40"],["2022-12-20","2.1016","-0.72","-0.77"],["2022-12-19","2.0891","-0.72","-0.77"],
["2022-12-18","1.9733","-0.77","-3.29"],["2022-12-17","0.7071","-1.64","-1.46"],
["2022-12-16","0.6967","-1.62","-1.46"],["2022-12-12","1.0440","-0.40","-0.40"]]
columns = ["日期","数值2","数值6","数值88"]
df = pd.DataFrame(data, columns=columns)

data = [["2022-12-20","8","6"],["2022-12-18","56","3"],["2022-12-12","8","7"],
["2022-12-16","5","8"]]
columns = ["日期","A","B"]
df2 = pd.DataFrame(data, columns=columns)

# 使用日期列将 df2 和 df 合并,设置 how='left' 以便保留 df2 中的所有日期
merged_df = df2.merge(df[['日期', '数值2']], on='日期', how='left')

# 将 '数值2' 列转换为数值类型
merged_df['数值2'] = pd.to_numeric(merged_df['数值2'], errors='coerce')

# 计算新列 'C'
merged_df['C'] = merged_df['数值2'] * 1.5 + pd.to_numeric(merged_df['A'])

print(merged_df)


这段代码将计算出 df2 数据帧的新列 "C"。merge 函数用于根据日期列合并数据帧,how='left' 参数保证了保留 df2 中的所有日期。然后,将 '数值2' 列转换为数值类型,并计算新列 'C'。
页: [1]
查看完整版本: 想通过另一个数据帧的值,增加本帧新增列的值,求帮忙,谢谢