python - 使用 pandas 创建新列时的条件分割

标签 python python-3.x pandas

我有一个数据,在“类型”列中,我有一组货币。我根据这些货币创建了新专栏。但我不知道如何给出一个条件,比如类型是 btc,然后创建这些列,就像我在该列中有更多类别一样。示例数据如下所示。

给定:

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

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

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

但我想要的是所有类型。

最佳答案

您可以按唯一值循环并为由 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

关于python - 使用 pandas 创建新列时的条件分割,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55862361/

相关文章:

python - Pandas 中有矢量化的 string.format 吗?

python - 用Python的statsmodels的OLS线性回归进行曲线拟合时,公式中的常数如何选择?

python - 在列表中的元素之间添加元素

python-3.x - 使用Pydrive按modifiedTime查询文件

python-3.x - 改变先知情节的特点

python - 将 pandas 列转换为 JSON 字符串

Python - 为什么通配符位在这里不起作用?

python - 我可以在 @app.before_request 中为我的 flask 请求对象附加一个值并将其转发给端点 View 函数吗?

python-3.x - plt.imshow() 没有正确显示 numpy 矩阵

python - 在 Pandas 中按列名选择两组列