【问题标题】:Better way to move list to csv?将列表移动到 csv 的更好方法?
【发布时间】:2019-07-24 02:53:20
【问题描述】:

所以我有列表的数据框。

这是数据框的代码:

Cafe_dataframe = pd.DataFrame({'카페 URL' : URL_LIST,
                            '카페명' : CafeTitle,
                            '카테고리명' : Category_Name,
                            '글쓴이ID' : NaverID,
                            '포스트 제목' : PostTitle,
                            '포스트일' : Posting_Date,
                            '조회수' : The_Number_of_Views,
                            '비디오수' : The_Number_of_Video,
                            '그림수' : The_Number_of_Picture,
                            '댓글수' : The_Number_of_Comment,
                            '글자수' : The_Number_of_Characters,
                            '키워드수' : The_Number_of_Keyword
                           })

Cafe_dataframe.to_csv('cafe_data.csv', index=True, encoding='UTF8')

path="./cafe_data.csv"
with open(path, 'r', encoding='UTF8', errors='replace') as infile, open('cafe_data_.csv', 'w', encoding='euc-kr', errors='replace') as outfile:
inputs = csv.reader(infile)
output = csv.writer(outfile)

for index, row in enumerate(inputs):
    output.writerow(row)

os.remove('cafe_data.csv')

并引发此错误:

ValueError: arrays must all be same length

现在,我知道dataframe 不能使用不同长度的列表,我检查了每个列表的长度,结果发现URL_LIST1000 元素,而其他只有755.

但我需要的是用列表创建csv 文件的方法无论它们的长度如何

有没有其他方法可以用列表创建CSV 文件?

或者无论如何忽略ValueError并仍然创建pandas dataframe

【问题讨论】:

  • 所以您想将URL_LIST 保留到最后并用nan 填充其余列?
  • @Chris 没关系。无论每个列表的长度如何,任何创建 CSV 文件的方法对我来说都可以。

标签: python python-3.x pandas list


【解决方案1】:

使用collections.OrderedDictitertools.zip_longest

from collections import OrderedDict
from itertools import zip_longest

d = OrderedDict({"A": [0,1], "C": [0,1,2,4], "B": [0,1,2]})

df = pd.DataFrame(list(zip_longest(*d.values())), columns = d.keys())
print(df)
     A  C    B
0  0.0  0  0.0
1  1.0  1  1.0
2  NaN  2  2.0
3  NaN  4  NaN

注意:OrderedDict 用于确保d.values()d.keys() 的顺序正确。如果您使用的是python 3.6或更高版本,正常dict就可以了。

【讨论】:

  • 一个简单的问题:是否必须列出 d = OrderedDict({"A": [0,1], "C": [0,1,2,4], " B": [0,1,2]})?我可以简单地将其替换为列表的名称吗?
  • 既然你已经有了dict,就把它换成d = OrderedDict(your_dict_that_is_inside_pd.DataFrame) ;)
  • 澄清一下,您要转换的内容不是列表。它称为列表的dict,其中dict 的键是您的names(即“카페 URL”),值是相应的列表。感觉您对这些术语有些困惑。
猜你喜欢
  • 2016-04-04
  • 1970-01-01
  • 2017-06-24
  • 2015-03-03
  • 1970-01-01
  • 1970-01-01
  • 2011-01-07
  • 2023-04-06
  • 1970-01-01
相关资源
最近更新 更多