【问题标题】:Pandas pct_change on only one column in the data frame to create a new columnPandas pct_change 仅在数据框中的一列上创建新列
【发布时间】:2021-08-03 13:46:30
【问题描述】:

我正在尝试在我的 pandas 数据框中添加一个新列,用于我的数据框中特定列的每日百分比变化。每当我尝试使用 pct_change() 方法时,它都会创建一个新数据框并将 pct_change() 应用于 df 中的所有列。下面是我目前拥有的表格:

new_date Name sentiment_polarity sentiment_score engagement engagement_polarity_score engagement_sentiment_score
0 2020-01-01 Bitcoin 0.342000 0.107069 6.142000 -0.325000 0.589380
1 2020-01-01 Cardano 0.334572 0.133310 11.256506 8.866171 2.509937
2 2020-01-01 Dogecoin 0.434783 0.155303 13.173913 11.121739 2.742231
3 2020-01-01 Ethereum 0.389000 0.133417 6.121000 4.652000 1.480854
4 2020-01-01 Stellar 0.759000 0.216281 7.437000 6.385000 1.851542
5 2020-01-02 Bitcoin 0.202000 0.067189 4.512000 1.536000 0.568809
6 2020-01-02 Cardano 0.307971 0.120505 17.282609 5.355072 1.606946
7 2020-01-02 Dogecoin 0.266667 0.095962 2.266667 1.276190 0.553433
8 2020-01-02 Ethereum 0.244000 0.098055 9.670000 4.583000 1.637720
9 2020-01-02 Stellar 0.729000 0.206842 5.765000 4.617000 1.093504

我希望在末尾有另一列,用于记录参与度_sentiment_score 列的每日百分比变化。

我尝试使用下面的 sn-p 但出现错误:

Bit['Daily % Sentiment Change'] = Bit.pct_change(axis=1)['engagement_sentiment_score']

错误消息:TypeError: /: 'str' 和 'str' 的操作数类型不受支持

然后我检查了engagement_sentiment_score 列中值的数据类型,它说它们是浮点数,所以我不确定为什么会出现这个错误。

感谢您的帮助!

【问题讨论】:

    标签: python pandas dataframe numpy methods


    【解决方案1】:

    使用 select_dtypes() 仅选择 int 和 float 值:

    Bit['Daily % Sentiment Change'] =(Bit.select_dtypes(include=['int','float'])
                                         .pct_change(axis=1)['engagement_sentiment_score'])
    

    【讨论】:

    • 谢谢。我不再收到错误,但看起来计算不是我所预期的。当我尝试进行健全性检查时,新列未计算每日百分比变化。
    • @J.Smith 所以试试Bit['engagement_sentiment_score'].pct_change()
    • 知道了!谢谢,Anurag,非常感谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-04
    • 2016-04-20
    • 1970-01-01
    • 1970-01-01
    • 2013-07-16
    • 1970-01-01
    相关资源
    最近更新 更多