Pythonic插入数据帧列并从列表中的每一列计算其值的方法
我有一个DataFrame列(来自我的项目),打印方式如下:Pythonic插入数据帧列并从列表中的每一列计算其值的方法,python,python-3.x,pandas,dataframe,Python,Python 3.x,Pandas,Dataframe,我有一个DataFrame列(来自我的项目),打印方式如下: ticker 2021-02-11 21:04 2021-01-12_close 2020-02-11_close 2016-02-11_close 0 AAPL 134.94 128.607819 79.287888 21.787796 1 MSFT 244.20 214.929993 182.5
ticker 2021-02-11 21:04 2021-01-12_close 2020-02-11_close 2016-02-11_close
0 AAPL 134.94 128.607819 79.287888 21.787796
1 MSFT 244.20 214.929993 182.506607 45.343704
这将给出一个股票代码及其当前价格,然后是给定日期的收盘价。我正在寻找一种类似python的方法,在每个X_close
列之后,插入一个X_return
列,并计算当前价格和X
价格之间的回报。做这件事的好方法是什么
谢谢
编辑:当我说“计算回报”时,我的意思是,例如,做:
((134.94 - 128.607819) / 128.607819) * 100
因此,简单地使用div()
或sub()
是不太令人满意的。试试:
df.filter
选择关闭
列.sub
减去所选列排序索引对列进行排序
。你可能需要玩这个df.join(df.filter(like='close').sub(df['2021-02-11 21:04'], axis=0)
.rename(columns=lambda x: x.replace('close','return'))
).sort_index(axis=1)
尝试:
df.filter
选择关闭
列.sub
减去所选列排序索引对列进行排序
。你可能需要玩这个df.join(df.filter(like='close').sub(df['2021-02-11 21:04'], axis=0)
.rename(columns=lambda x: x.replace('close','return'))
).sort_index(axis=1)
好问题。其思想是首先简单地创建新列并将其连接到数据帧
df_returns = (df[cols].div(df["2021-02-11 21:04:00"], axis=0)).rename(columns = (lambda x: x.split('_')[0]+'_return'))
df_new = pd.concat([df, df_returns], axis=1).sort_index(axis=1)
或者,您可以使用索引以获得更好的图形实用程序:
df_new[df_new.columns[:-3:-1].union(df_new.columns[:-2], sort=False)]
对于更定制的方法,请使用apply方法
df_returns = (df[cols].apply(foo, axis=0))
def foo(s: pd.Series):
#Series specific changes
ans = pd.Series()
for i in s.shape[0]:
ans.iloc[i] = some_func(s.iloc[i])
#Rename series index for convenience
希望这有帮助!在某些函数()中,您可以执行任何您喜欢的操作。好问题。其思想是首先简单地创建新列并将其连接到数据帧
df_returns = (df[cols].div(df["2021-02-11 21:04:00"], axis=0)).rename(columns = (lambda x: x.split('_')[0]+'_return'))
df_new = pd.concat([df, df_returns], axis=1).sort_index(axis=1)
或者,您可以使用索引以获得更好的图形实用程序:
df_new[df_new.columns[:-3:-1].union(df_new.columns[:-2], sort=False)]
对于更定制的方法,请使用apply方法
df_returns = (df[cols].apply(foo, axis=0))
def foo(s: pd.Series):
#Series specific changes
ans = pd.Series()
for i in s.shape[0]:
ans.iloc[i] = some_func(s.iloc[i])
#Rename series index for convenience
希望这有帮助!您可以在某些函数()中执行任何您喜欢的操作。将给出的答案中的想法与我自己的结合起来,以下是我的解决方案:
def calculate_returns(df):
print(df)
print()
# Get dataframe of return values
returns_df = df.apply(calculate_return_row, axis=1)
# Append returns df to close prices df
df = pd.concat([df, returns_df], axis=1).sort_index(axis=1, ascending=False)
# Rearrange columns so that close price precedes each respective return value
return_cols = df.columns[2::2]
close_cols = df.columns[3::2]
reordered_cols = list(df.columns[0:2])
reordered_cols = reordered_cols + [col for idx, _ in enumerate(return_cols) for col in [close_cols[idx], return_cols[idx]]]
df = df[reordered_cols]
print(df)
return df
def calculate_return_row(row: pd.Series):
current_price = row[1]
close_prices = row[2:]
returns = [calculate_return(current_price, close_price) for close_price in close_prices]
index = [label.replace('close', 'return') for label in row.index[2:]]
returns = pd.Series(returns, index=index)
return returns
def calculate_return(current_val, initial_val):
return (current_val - initial_val) / initial_val * 100
这样可以避免循环,并将返回列放在关闭列之后:
ticker 2021-02-12 20:37 2021-01-13_close 2020-02-12_close 2016-02-12_close
0 AAPL 134.3500 130.694702 81.170799 21.855232
1 MSFT 243.9332 216.339996 182.773773 46.082863
ticker 2021-02-12 20:37 2021-01-13_close 2021-01-13_return 2020-02-12_close 2020-02-12_return 2016-02-12_close 2016-02-12_return
0 AAPL 134.3500 130.694702 2.796822 81.170799 65.515187 21.855232 514.726938
1 MSFT 243.9332 216.339996 12.754555 182.773773 33.461818 46.082863 429.336037
谢谢 结合给出的答案和我自己的想法,以下是我的解决方案:
def calculate_returns(df):
print(df)
print()
# Get dataframe of return values
returns_df = df.apply(calculate_return_row, axis=1)
# Append returns df to close prices df
df = pd.concat([df, returns_df], axis=1).sort_index(axis=1, ascending=False)
# Rearrange columns so that close price precedes each respective return value
return_cols = df.columns[2::2]
close_cols = df.columns[3::2]
reordered_cols = list(df.columns[0:2])
reordered_cols = reordered_cols + [col for idx, _ in enumerate(return_cols) for col in [close_cols[idx], return_cols[idx]]]
df = df[reordered_cols]
print(df)
return df
def calculate_return_row(row: pd.Series):
current_price = row[1]
close_prices = row[2:]
returns = [calculate_return(current_price, close_price) for close_price in close_prices]
index = [label.replace('close', 'return') for label in row.index[2:]]
returns = pd.Series(returns, index=index)
return returns
def calculate_return(current_val, initial_val):
return (current_val - initial_val) / initial_val * 100
这样可以避免循环,并将返回列放在关闭列之后:
ticker 2021-02-12 20:37 2021-01-13_close 2020-02-12_close 2016-02-12_close
0 AAPL 134.3500 130.694702 81.170799 21.855232
1 MSFT 243.9332 216.339996 182.773773 46.082863
ticker 2021-02-12 20:37 2021-01-13_close 2021-01-13_return 2020-02-12_close 2020-02-12_return 2016-02-12_close 2016-02-12_return
0 AAPL 134.3500 130.694702 2.796822 81.170799 65.515187 21.855232 514.726938
1 MSFT 243.9332 216.339996 12.754555 182.773773 33.461818 46.082863 429.336037
谢谢 谢谢!我试试这个。如何进行自定义操作而不是减法?以某种方式使用
map()
吗?谢谢!我试试这个。如何进行自定义操作而不是减法?以某种方式使用map()
吗?谢谢!这让我很接近,但除了直接除法之外,我实际上想做的是(df[cols]-df[“2021-02-11 21:04:00]”)/df[“2021-02-11 21:04:00”]
。如何使用自定义函数而不是div
?嗯。。你需要这样做。我已经更新了帖子。谢谢!这让我很接近,但除了直接除法之外,我实际上想做的是(df[cols]-df[“2021-02-11 21:04:00]”)/df[“2021-02-11 21:04:00”]
。如何使用自定义函数而不是div
?嗯。。你需要这样做。我已经更新了帖子。