【问题标题】:For Loop - TypeError: must be str, not int [duplicate]For Loop - TypeError:必须是 str,而不是 int [重复]
【发布时间】:2019-04-23 08:36:20
【问题描述】:

我在尝试创建 for 循环时有点困惑。

我有一个包含一些推文信息的数据框,我需要 2 列用于此循环:tweet_idexpanded_urls。 我的数据框中有些情况下expanded_urls 不完整,它们只是'twitter.com/xxx/status/'。但是正确的链接在状态之后有推文 ID,例如:twitter.com/xxx/status/1234567890

所以,我试过这个:

for i in line:
    twitter_archive_master['expanded_urls'] = np.where(twitter_archive_master['expanded_urls'] == 'https://twitter.com/xxx/status/', ('https://twitter.com/xxx/status/'+ twitter_archive_master.tweet_id), twitter_archive_master['expanded_urls'])

所以我选择了带有这个不完整 URL 的每一行并尝试添加他们的 ID,但是我收到了这个错误:

TypeError: must be str, not int

我做错了什么?

两列都是对象。

【问题讨论】:

  • ('https://twitter.com/xxx/status/'+ twitter_archive_master.tweet_id) 也许这需要明确地做成一个str?
  • 是的,推文 ID 不是字符串。它以 int 形式返回,因此需要显式转换;添加一个字符串和一个 int 不会隐式转换。如果您愿意,也可以使用字符串插值、格式化字符串或 f 字符串,例如'http://url.com/{:d}'.format(tweet_id).

标签: python pandas numpy for-loop replace


【解决方案1】:

尝试将id转为字符串类型

for i in line:
    twitter_archive_master['expanded_urls'] = np.where(twitter_archive_master['expanded_urls'] == 
                                                       https://twitter.com/xxx/status/',
                                                       ('https://twitter.com/xxx/status/'
                                                        +
                                                        str(twitter_archive_master.tweet_id)),
                                                       twitter_archive_master['expanded_urls'])

【讨论】:

  • 查看How do I format my code blocks 以确保在所有平台上的可读性并更好地与辅助工具集成。
  • 哦……完美!!它起作用了......如果它已经是STR,为什么我要把它转换为str?有什么想法吗?也许是因为它是一个数字,如果我不告诉它是一个 str,python 不知道?
猜你喜欢
  • 1970-01-01
  • 2017-12-08
  • 1970-01-01
  • 2018-07-23
  • 2018-04-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多