簡體   English   中英

從 pandas 中的分塊 csv 文件中保存多個 csv 文件

[英]Saving multiple csv files from chunked csv file in pandas

我正在嘗試將一個非常大的(約 2500 萬行)csv 文件加載到 pandas 中。 我正在分塊這個文件,一次 100,000 行,並附加一個新創建的 dataframe,它基本上計算分塊 dataframe 列中某些單詞的出現次數。 當我保存第一個塊時,一切正常,並且塊並排連接到新創建的 dataframe。 然而,由於某種原因,第二個塊是對角連接的。 我的意思是分塊的 dataframe 現在是 200,000 行,前 100,000 行是空的,新創建的 dataframe 與前 100,000 行並排連接。 如何解決此問題並將每個塊與新創建的 dataframe 並排連接並將每個塊保存到單獨的 csv 文件中?

我的代碼:

import pandas as pd
from pandas.core.frame import DataFrame

chunk = 1

for df in pd.read_csv('all_comments_data.csv', chunksize=100000):
    dict_to_append = {}

    with open('conflict_words.txt') as f:
        for word in f.readlines():
            dict_to_append[word.strip()] = []
    
    index = 0

    for comment in df['comment'].to_numpy():
        word_list = str(comment).split(" ")
        for conflict_word in dict_to_append.keys():
            dict_to_append[conflict_word].append(word_list.count(conflict_word))
        print(index)
        index +=1


    df_to_append = pd.DataFrame(dict_to_append)
    final_df = pd.concat([pd.DataFrame(df), df_to_append], axis=1)
    final_df.to_csv(f"all_comments_data_with_conflict_scores_{chunk}.csv")
    chunk += 1 
What I need dataframes to look like:

---------------------------
|            |            |
|  chunk     | new dframe |
|            |            |
---------------------------

What the dataframes look like after the first chunk:

---------------------------
|            |            |
|            | new dframe |
|            |            |
---------------------------
|            |            |
| chunk      |            |
|            |            |
---------------------------

當按列運行pd.concat時,pandas 將嘗試通過索引匹配行:

df1 = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]}, index=[1, 3, 5])
df2 = pd.DataFrame({"A": [4, 5, 6], "B": [7, 8, 9]}, index=[2, 4, 6])
df3 = pd.concat([df1, df2], axis=1)
print(df3)

     A    B    A    B
1  1.0  4.0  NaN  NaN
2  NaN  NaN  4.0  7.0
3  2.0  5.0  NaN  NaN
4  NaN  NaN  5.0  8.0
5  3.0  6.0  NaN  NaN
6  NaN  NaN  6.0  9.0

如果您希望chunknew dframe在連接后並排放置,則需要確保它們都具有相同的行索引。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM