将列表移动到csv的更好方法?

2024-05-20 12:11:42 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我有列表的数据框架。你知道吗

以下是数据帧的代码:

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文件,而不管它们的长度。你知道吗

有没有其他方法可以用list创建CSV文件?你知道吗

还是有什么方法可以忽略ValueError而仍然创建pandas dataframe?你知道吗


Tags: ofcsvthe数据方法urlnumberdataframe
1条回答
网友
1楼 · 发布于 2024-05-20 12:11:42

使用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()的顺序正确。如果您使用的是python3.6或更高版本,那么正常的dict就可以了。你知道吗

相关问题 更多 >