【问题标题】:TypeError: argument of type 'float' is not iterable - reshape csv fileTypeError:'float' 类型的参数不可迭代 - 重塑 csv 文件
【发布时间】:2020-08-17 17:03:24
【问题描述】:

我有一个 csv 文件,其中第一列代表数字 ID,一列代表用户 cmets。
ID 列中遗漏了一些 cmets。因此,我假装检查 ID 列中的每一行,如果它不是数字,则复制该行并将其粘贴到 Comments 列中(ID 列中的最后一个 True)。print(clean_order):
web_scraper_order ... 评论
0 1593612265-26203 ... 伦敦是(...)
1 1593612270-26346 ... 我不 (...)
2 1593612265-26217 ...以及(...)
3 1593612290-26579 ... 我唱歌 (...)
4 1593612256-26064 ... 您的第一个 (...)
……………… 第3074章 3075 国家统计局网站为...... NaN
第3076章 3077 查看可以下载的议会网站... ... NaN
第3078章 我真的同意你的观点,这是一个很大的耻辱... ... NaN

clean_order.info():

RangeIndex:3079 个条目,0 到 3078
数据列(共 16 列):

列非空计数 Dtype

0 web_scraper_order 2722 非空对象
1 web-scraper-start-url 2324 非空对象
2 Discussions_Link 2141 非空对象
3 Discussions_Link-href 1940 非空对象
4 分页 1820 非空对象
5 Pagination-href 1757 非空对象
6 Title_Discussion 1720 非空对象
7 已发布 1698 个非空对象
8 Published_Date 1679 非空对象
9 科目 1672 非空对象
10 讨论 1660 非空对象
11 条评论 1653 非空对象
12 Pagination_Comments 520 非空对象
13 Pagination_Comments-href 517 非空对象
数据类型:对象(16) 内存使用量:192.5+ KB

我的代码:

import pandas as pd

clean_order = pd.read_csv('C:/Users/(...)/Page_Clean_test.csv', 'w+', delimiter=';', skiprows=0, low_memory=False)
save_row = 0

for L in range(0, 1500):
     if "159361" in clean_order['web_scraper_order'][L]:
         save_row = L
     else:
         clean_order['Comments'][save_row] = clean_order['Comments'][save_row] + clean_order['web_scraper_order'][L]

错误:
Traceback(最近一次调用最后一次): 文件“C:/Users/suiso/PycharmProjects/Teste_SA/Change web_scraper_order.py”,第 12 行,在 如果 clean_order['web_scraper_order'][L] 中的“159361”: TypeError: 'float' 类型的参数不可迭代

【问题讨论】:

  • 所以您的 order 列是一个对象,但其中也有 np.nans,这可能就是您收到错误的原因
  • 当我使用你的代码时,这个错误返回:NameError: name 'np' is not defined。所以,我做了一些研究,意识到我必须做的是:import numpy as np。当我执行代码时,又出现了一个错误:TypeError: object of type 'float' has no len ()
  • 我的错应该是df.web_scraper_order = df.web_scraper_order.fillna('')...不过请检查我的答案
  • 适用于fillna() 代码。现在我只需要将剩余的列复制到注释行。例如:column1:“我正在(...)”; column2:在第 915 行到上一个 ID 列中的“它在 (...) 中完成”。
  • 我会检查 pandas 中的矢量化解决方案并提供反馈。

标签: python pandas for-loop if-statement


【解决方案1】:

添加.fillna() 的解决方案应该可以完成工作。但是,习惯于 pandas 中的矢量化解决方案是件好事。这是另一种选择。

从这些数据开始

np.random.seed(0)
df = pd.DataFrame(
    [['159361' + str(x), 'first comment'] if np.random.choice([True, False])
        else ['comment' + str(x), ''] for x in range(3000)], columns=['ID', 'Comment'])
df.loc[np.random.randint(0, 3000, 200), 'ID'] = np.nan

>>> print(df)
               ID        Comment
0         1593610  first comment
1        comment1
2        comment2
3         1593613  first comment
4        comment4
...           ...            ...
2995  comment2995
2996  comment2996
2997   1593612997  first comment
2998   1593612998  first comment
2999  comment2999

[3000 rows x 2 columns]

现在通过获取有效 ID 对 ID 列进行分组

coms = df.groupby(
    df.ID.str.contains('159361').cumsum() # artificial index, increases with every valid ID
    ).ID.apply(list) # returns a list of values for each valid ID

>>> print(coms)
ID
True                          [1593610, comment1, comment2]
2         [1593613, comment4, comment5, comment6, commen...
3.0                                              [15936111]
4.0                                              [15936112]
5.0                                              [15936114]
                                ...
1362.0               [1593612984, comment2986, comment2987]
1363.0                            [1593612988, comment2989]
1364.0    [1593612990, comment2991, comment2992, comment...
1365.0                                         [1593612997]
1366.0                            [1593612998, comment2999]
Name: ID, Length: 1366, dtype: object

现在将每个列表的第一个元素设置为索引并加入其余元素。

coms.index = coms.str.get(0)
coms = coms.str.slice(start=1).str.join('; ')

>>> print(coms)
1593610                                      comment1; comment2
1593613       comment4; comment5; comment6; comment7; commen...
15936111
15936112
15936114
                                    ...
1593612984                             comment2986; comment2987
1593612988                                          comment2989
1593612990    comment2991; comment2992; comment2993; comment...
1593612997
1593612998                                          comment2999
Name: ID, Length: 1366, dtype: object

追加到df中的cmets列

df = df.loc[df.ID.isin(coms.index), :] \ # use only rows with valid IDs
    .set_index('ID') # and set IDs as index so it can be aligned with coms.index
df.Comment = df.Comment + '; ' + coms # join columns

>>> print(df)
ID
1593610                     first comment; comment1; comment2
1593613     first comment; comment4; comment5; comment6; c...
15936111                                      first comment;
15936112                                      first comment;
15936114                                      first comment;
...                                                       ...
1593612984            first comment; comment2986; comment2987
1593612988                         first comment; comment2989
1593612990  first comment; comment2991; comment2992; comme...
1593612997                                    first comment;
1593612998                         first comment; comment2999

[1366 rows x 1 columns]

【讨论】:

  • 我尝试了 pandas 中的矢量化解决方案,并根据我的问题进行了调整,效果很好。但是,正如我在上面的评论中所说;我还需要添加出现在第 2、3 列等中的 cmets。
  • 我了解您也希望为更多列执行此操作。请注意,这不是您问题的一部分,因此在我的回答中没有考虑。我建议您发布一个新问题并链接到该问题作为后续问题。如果你觉得这个答案满足你在这篇文章中的要求,你可以选择“接受的答案”并投票。
  • 如果您发布后续问题,请在df.head(10).to_dict() 中包含您的数据样本,并确保前几行代表您的问题。另外,请在此处评论并附上指向该新问题的链接,我很乐意查看。编码愉快!
  • 好的,如果我需要创建另一个帖子来澄清我对这个主题的疑问,我会转发链接以继续研究。如果我找到解决方案,我会与您和社区分享。非常感谢。 @RichieV
  • 我发布了关于这个主题的另一个问题。如果你能帮助我,谢谢。 stackoverflow.com/questions/63505440/…@RichieV
猜你喜欢
  • 2020-05-07
  • 1970-01-01
  • 2022-11-08
  • 2017-01-31
  • 2020-01-04
  • 2019-01-30
  • 2016-02-15
  • 2021-01-15
相关资源
最近更新 更多