|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
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"][0] = df["数值2"]*1.5+df2["A"][0],。。。。。依此类推
求大师帮忙,谢谢
可以使用 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'。
|
|