|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
data = [["2022-12-21",None,"会求数据","-0.40"],["2022-12-20","2.1016","会求数据","-0.77"],["2022-12-19","3698得息56.8","会求数据","-0.77"],
["2022-12-18","1.9733","会求数据",""],["2022-12-17","698分得56","会求数据",""],
["2022-12-16","","",""],["2022-12-12","","会求数据","-0.40"]]
columns = ["日期","B","C","D"]
df = pd.DataFrame(data, columns=columns)
由于考虑不周,没设想None的情况,特再发请求
想求上面数据帧中c列的数据:
C列数据由B列和/或D列相应行决定:
如果B列某行是空或None,D列有数字,则C列对应行数据就是D列对应行数字除以0.28,
如果B列行是纯数字,则C列对应行数据就是B列数字加55,
如果B列行是含数字的字符串,则C列对应行数据就是B列字符串中提出的第组数字除以D列不为零的数字
其它情况,C列不作任何计算
求大师帮忙指导,谢谢!
本帖最后由 歌者文明清理员 于 2023-4-17 20:41 编辑
根据您提供的条件,可以使用如下代码计算C列的值: import pandas as pd
import re
# 定义一个函数用于从字符串中提取数字
def extract_number(string):
pattern = r'\d+\.*\d*'
match = re.search(pattern, string)
if match:
return float(match.group())
else:
return None
# 定义一个函数用于计算C列的值
def calculate_c_value(row):
b_value = row['B']
d_value = row['D']
if pd.isna(b_value):
if pd.notna(d_value):
return float(d_value) / 0.28
else:
return None
elif isinstance(b_value, (int, float)):
return float(b_value) + 55
elif isinstance(b_value, str):
b_number = extract_number(b_value)
if b_number is not None and pd.notna(d_value) and d_value != '0':
return b_number / float(d_value)
else:
return None
else:
return None
# 创建DataFrame并应用计算函数
data = [["2022-12-21",None,"会求数据","-0.40"],
["2022-12-20","2.1016","会求数据","-0.77"],
["2022-12-19","3698得息56.8","会求数据","-0.77"],
["2022-12-18","1.9733","会求数据",""],
["2022-12-17","698分得56","会求数据",""],
["2022-12-16","","",""],
["2022-12-12","","会求数据","-0.40"]]
columns = ["日期","B","C","D"]
df = pd.DataFrame(data, columns=columns)
df['C'] = df.apply(calculate_c_value, axis=1)
这个代码将根据您提供的条件对数据帧进行计算和更新,为C列填充相应行的值。
|
|