使用 pandas 创建新列的条件拆分 [英] Conditional split on creating new columns using pandas

查看:102
本文介绍了使用 pandas 创建新列的条件拆分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据,其中在类型"列中有一组货币.我根据这些货币创建了新列.但是我不确定如何给条件,例如类型是否为btc,然后创建这些列,就像明智的那样,我在该列中有更多类别.示例数据如下所示.

I have a data where in column 'Type', I have set of currencies. I created new columns based on these currencies. But i am not sure how to give a condition like if the type is btc then create these columns, like wise i have more categories in that column. The sample data looks like this.

给出:

Type    Last                 
ada     3071.56         
ada     3097.82          
btc     1000.00
ada     2000.00
btc     3000.00
eur     1000.00
eur     1500.00

预期:

Type    Last        changbtwread_ada    changbtwread_btc  changbtwread_eur         
ada     3071.56          Nan                 Nan               Nan
ada     3097.82          26.0                Nan               Nan
btc     1000.00          Nan                 Nan               Nan 
ada     2000.00         -1097.82             Nan               Nan
btc     3000.00          Nan                 2000              Nan
eur     1000.00          Nan                 Nan               Nan
eur     1500.00          Nan                 Nan               500

我试图在一种类型的读取之间创建此更改的代码如下:

The code i tried to create this change between reading for one type is as follow:

df['changbtwread'] = df['Last'].diff()

但是我想要的是所有类型的东西.

But what i want is for all types.

推荐答案

您可以按唯一值循环,并与f-string s创建的新列创建差异:

You can loop by unique values and create difference to new columns created by f-strings:

for v in df['Type'].unique():
    df[f'changbtwread_{v}'] = df.loc[df['Type'].eq(v), 'Last'].diff()
print (df)
  Type     Last  changbtwread_ada  changbtwread_btc  changbtwread_eur
0  ada  3071.56               NaN               NaN               NaN
1  ada  3097.82             26.26               NaN               NaN
2  btc  1000.00               NaN               NaN               NaN
3  ada  2000.00          -1097.82               NaN               NaN
4  btc  3000.00               NaN            2000.0               NaN
5  eur  1000.00               NaN               NaN               NaN
6  eur  1500.00               NaN               NaN             500.0

这篇关于使用 pandas 创建新列的条件拆分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆