|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
import pandas as pd
data = [["2022-12-21","会求数据","","-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)
想求上面数据帧中c列的数据:
C列数据由B列和/或D列相应行决定:
如果B列某行是空,D列有数字,则C列对应行数据就是D列对应行数字除以0.28,
如果B列行是纯数字,则C列对应行数据就是B列数字加55,
如果B列行是含数字的字符串,则C列对应行数据就是B列字符串中提出的第组数字除以D列不为零的数字
其它情况,C列不作任何计算
求大师帮忙指导,谢谢!
您好!根据您的需求,可以通过遍历数据帧的行并根据条件对C列进行相应计算。以下是解决方案:
import pandas as pd
import re
data = [["2022-12-21", "会求数据", "", "-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)
for index, row in df.iterrows():
if row['B'] == '' and row['D'] != '':
df.at[index, 'C'] = float(row['D']) / 0.28
elif row['B'].replace(".", "").isdigit():
df.at[index, 'C'] = float(row['B']) + 55
else:
numbers = re.findall(r'\d+\.?\d*', row['B'])
if len(numbers) > 0 and row['D'] != '':
df.at[index, 'C'] = float(numbers[0]) / float(row['D'])
print(df)
这段代码首先遍历数据帧的每一行,然后根据您所给的条件对C列进行计算。希望这个解决方案对您有所帮助!
|
|