[英]Merging dataframes iteratively with pandas
我正在嘗試使用read_csv合並pandas中的兩個數據幀。 但是我的一個數據幀(在這個例子中為d1
)對我的計算機來說太大了,所以我在read_csv
使用了iterator
參數。
假設我有兩個數據幀
d1 = pd.DataFrame({
"col1":[1,2,3,4,5,6,7,8,9],
"col2": [5,4,3,2,5,43,2,5,6],
"col3": [10,10,10,10,10,4,10,10,10]},
index=["paul", "peter", "lauren", "dave", "bill", "steve", "old-man", "bob", "tim"])
d2 = pd.DataFrame({
"yes/no": [1,0,1,0,1,1,1,0,0]},
index=["paul", "peter", "lauren", "dave", "bill", "steve", "old-man", "bob", "tim"])
我需要合並它們,以便每行捕獲每個人的所有數據,所以相當於:
pd.concat((d1,d2), axis=1,join="outer")
但由於我無法將d1放入內存,我一直在使用read_csv
(我正在使用read_csv
因為我已經處理了一個巨大的文件並將其保存為.csv格式,所以想象一下我的數據幀d1包含在文件test.csv
)。
itera = pd.read_csv("test.csv",index_col="index",iterator=True,chunksize=2)
但是,當我這樣做
for i in itera:
d2 = pd.concat((d2,i), axis=1,join="outer")
我的輸出是第二個數據幀附加的第一個數據幀。
我的輸出如下:
col1 col2 col3 yes/no
one NaN NaN NaN 1.0
two NaN NaN NaN 0.0
three NaN NaN NaN 1.0
four NaN NaN NaN 0.0
five NaN NaN NaN 1.0
six NaN NaN NaN 1.0
seven NaN NaN NaN 1.0
eight NaN NaN NaN 0.0
nine NaN NaN NaN 0.0
one 1.0 5.0 10.0 NaN
two 2.0 4.0 10.0 NaN
three 3.0 3.0 10.0 NaN
four 4.0 2.0 10.0 NaN
five 5.0 5.0 10.0 NaN
six 6.0 43.0 4.0 NaN
seven 7.0 2.0 10.0 NaN
eight 8.0 5.0 10.0 NaN
nine 9.0 6.0 10.0 NaN
希望我的問題有道理:)
我認為你正在尋找組合第一種方法。 它基本上使用read_csv
迭代器中每個塊的值更新df1
。
import pandas as pd
from StringIO import StringIO
d1 = pd.DataFrame({
"col1":[1,2,3,4,5,6,7,8,9],
"col2": [5,4,3,2,5,43,2,5,6],
"col3": [10,10,10,10,10,4,10,10,10]},
index=["paul", "peter", "lauren", "dave", "bill", "steve", "old-man", "bob", "tim"])
#d2 converted to string tho use with pd.read_csv
d2 = StringIO("""y/n col5
paul 1
peter 0
lauren 1
dave 0
bill 1
steve 1
old-man 1
bob 0
tim 0
""")
#For each chunk update d1 with data
for chunk in pd.read_csv(d2, sep = ' ',iterator=True,chunksize=1):
d1 = d1.combine_first(chunk[['y/n']])
#Number formatting
d1['y/n'] = d1['y/n'].astype(int)
返回d1
看起來像:
col1 col2 col3 y/n
bill 5 5 10 1
bob 8 5 10 0
dave 4 2 10 0
lauren 3 3 10 1
old-man 7 2 10 1
paul 1 5 10 1
peter 2 4 10 0
steve 6 43 4 1
tim 9 6 10 0
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.