[英]How to move values from one dataframe to another in pandas?
I have a df1 that looks like this:我有一个 df1 看起来像这样:
Symbol Order Shares
Date
2009-01-14 AAPL BUY 150
2009-01-21 AAPL SELL 150
2009-01-21 IBM BUY 400
And df2 looks like this: df2 看起来像这样:
GOOG AAPL XOM IBM Cash
Date
2009-01-14 NaN NaN NaN NaN NaN
2009-01-21 NaN NaN NaN NaN NaN
I want to move the values in the first DF to the second so that the amount of shares populates under the appropriate stock symbol.我想将第一个 DF 中的值移动到第二个,以便在适当的股票代码下填充股票数量。 So the above would look like:所以上面看起来像:
GOOG AAPL XOM IBM Cash
Date
2009-01-14 NaN 150 NaN NaN NaN
2009-01-21 NaN -150 NaN 400 NaN
How would I move all values that I have in my first dataframe to the second dataframe?如何将第一个数据框中的所有值移动到第二个数据框中?
You really don't need df2
here.你真的不需要df2
在这里。 You can compute the result directly from df
using some simple reshaping functions set_index
, unstack
and reindex
.您可以直接从计算结果df
使用一些简单的重塑功能set_index
, unstack
和reindex
。 You just need the symbols list.您只需要符号列表。
(df.assign(Shares=np.where(df.Order == 'BUY', df.Shares, -df.Shares))
.drop('Order', 1)
.set_index('Symbol', append=True)['Shares']
.unstack(1)
.reindex(df2.columns, axis=1)) # you can replace df2.columns with a list
GOOG AAPL XOM IBM Cash
Date
2009-01-14 NaN 150.0 NaN NaN NaN
2009-01-21 NaN -150.0 NaN 400.0 NaN
Use np.select
to convert numbers to negative if Order == 'SELL'
then update
如果Order == 'SELL'
然后update
则使用np.select
将数字转换为负数
df['Shares'] = np.select([df['Order'] == 'SELL'], [-df['Shares']], df['Shares'])
df2.update(df.pivot(None, 'Symbol', 'Shares'))
GOOG AAPL XOM IBM Cash
Date
2009-01-14 NaN 150.0 NaN NaN NaN
2009-01-21 NaN -150.0 NaN 400.0 NaN
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.