【问题标题】:Comparing dataframes in Python to calculate difference比较 Python 中的数据帧以计算差异
【发布时间】:2021-05-20 13:30:26
【问题描述】:

我正在使用 Pandas df 抓取这个网站 (https://www.coingecko.com/en/coins/recently_added?page=1)。我想获取代币和价格的快照,然后在 10 秒后获取代币和价格的另一个快照,以查看代币是否已按价格移动。这是我用来执行此操作的代码:

import pandas as pd
import requests
import time

url = "https://www.coingecko.com/en/coins/recently_added?page=1"
df = pd.read_html(requests.get(url).text, flavor="bs4")
df = pd.concat(df).drop(["Unnamed: 0", "Unnamed: 1"], axis=1)
# print(df.head)
df_first = df[['Coin', 'Price']]
time.sleep(10)

url = "https://www.coingecko.com/en/coins/recently_added?page=1"
df = pd.read_html(requests.get(url).text, flavor="bs4")
df = pd.concat(df).drop(["Unnamed: 0", "Unnamed: 1"], axis=1)
df_last = df[['Coin', 'Price']]


df_merged = df_first.merge(df_last, left_on=['Coin'], right_on=['Coin'])
df_merged.set_index(['Coin'], inplace=True)
df_merged['pct_change'] = df_merged[['Price_x','Price_y']].pct_change(axis=1)['Price_y']
df_merged['greater_than_1'] = df_merged['pct_change'] > 10.00
print(df_merged)

当我运行代码时出现错误

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

不知道为什么。欢迎任何帮助

【问题讨论】:

标签: python


【解决方案1】:

因为Price 是一个字符串列。您可以使用df.info() 方法检查数据类型。

您需要将字符串 '$1,234.5' 转换为浮点数。您可以使用converters 参数来做到这一点:

def parse_price(x):
    return float(x.replace('$', '').replace(',', ''))

url = "https://www.coingecko.com/en/coins/recently_added?page=1"
converters = {"Price": parse_price}

df = pd.read_html(requests.get(url).text, flavor="bs4", converters=converters)

【讨论】:

    【解决方案2】:

    您正在尝试分割两个字符串。显然没有一种语言会喜欢这样!

    如果您将两者都转换为浮点数,那么它会起作用。有关转换列,请参见此处:

    https://datatofish.com/convert-string-to-float-dataframe/

    df['DataFrame Column'] = df['DataFrame Column'].astype(float)
    

    但是 - 看看你的问题 - 你真的确定这是你想要查看价格变化的方式吗?您不会考虑将其中一个 api 用于现有服务器,例如 Binance,并使用它们的代码流吗?

    【讨论】:

      猜你喜欢
      • 2014-01-06
      • 2019-02-10
      • 1970-01-01
      • 1970-01-01
      • 2022-08-07
      • 1970-01-01
      • 2022-11-29
      • 2020-06-10
      • 1970-01-01
      相关资源
      最近更新 更多