gpt4 book ai didi

python - 展平 Pandas Dataframes 中的列并引用原始资料

转载 作者:太空宇宙 更新时间:2023-11-04 08:42:55 25 4
gpt4 key购买 nike

如何在 pandas 数据框中展平两列?

例如

Task 1 : 

company-asset company-debt wealth
GOLD SILVER 2000.0
BRONZE IRON 4000.0
IRON GOLD 1500.0

现在我想要( Assets 为+,债务为负)

GOLD   SILVER   BRONZE   IRON
500 -2000 4000 -2500

Task 2:

Now i want to get the original dataframe with rows where value of
the columns in dataframe 2 is greater than -1000 and less than +1000.
So in the case above it will only be GOLD therefore we get this DF

company-asset company-debt wealth
GOLD SILVER 2000.0
IRON GOLD 1500.0

最佳答案

试试这个:

s = (df.set_index('wealth').stack()
.rename('metal')
.rename_axis(('wealth', 'type'))
.reset_index()
.pipe(lambda l: l.assign(wealth=l.wealth.where(l.type.str.endswith('asset'),
-l.wealth)))
.groupby('metal').wealth.sum())

s
#metal
#BRONZE 4000.0
#GOLD 500.0
#IRON -2500.0
#SILVER -2000.0
#Name: wealth, dtype: float64

metals = s[(s > -1000) & (s < 1000)].index
df[df['company-asset'].isin(metals) | df['company-debt'].isin(metals)]

# company-asset company-debt wealth
#0 GOLD SILVER 2000.0
#2 IRON GOLD 1500.0

关于python - 展平 Pandas Dataframes 中的列并引用原始资料,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43331525/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com