【问题标题】:Converting List to Dataframe, then Appending将列表转换为数据框,然后附加
【发布时间】:2020-04-05 01:25:05
【问题描述】:

我正在尝试将列表转换为 DataFrame。该列表来自一个文档,其中单词被单独分成单独的行。然后需要将该列表转换为 DataFrame。但是,在我运行我的 for 循环后,DataFrame 不包含任何信息。

import urllib.request
import pandas as pd
data = urllib.request.urlopen('https://www.w3.org/TR/PNG/iso_8859-1.txt')

wordlist = pd.DataFrame(columns = ['col1'])

for line in data:
        for word in line.split():
            print(word)
            wordlist.append({'col1': word}, ignore_index=True)

单词拆分正确:

b'The'
b'following'
b'are'
b'the'
b'graphical'
b'(non-control)'
b'characters'

但是附加的数据框返回:

print(wordlist)
Empty DataFrame
Columns: [col1]
Index: []

【问题讨论】:

    标签: python list dataframe append


    【解决方案1】:

    你可以试试这个,它直接从数据中拆分出来:

    import urllib.request
    import pandas as pd
    data = urllib.request.urlopen('https://www.w3.org/TR/PNG/iso_8859-1.txt')
    
    wordlist = pd.DataFrame(data.read().split(), columns = ['col1'])
    

    输出:

                 col1
    0          b'The'
    1    b'following'
    2          b'are'
    3          b'the'
    4    b'graphical'
    ..            ...
    853      b'SMALL'
    854     b'LETTER'
    855          b'Y'
    856       b'WITH'
    857  b'DIAERESIS'
    

    【讨论】:

      【解决方案2】:

      我使用了错误的语法

      for line in data:
              for word in line.split():
                  print(word)
                  wordlist = wordlist.append({'col1': word}, ignore_index=True)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-07-12
        • 2011-06-27
        • 1970-01-01
        • 2016-11-05
        • 2021-05-05
        • 2019-04-29
        相关资源
        最近更新 更多