[英]Add calculated column to pandas dataframe on the fly while iterating over the lines of a csv file?
我有一個很大的空格分隔的輸入文件input.csv
,我無法保存在內存中:
## Header
# More header here
A B
1 2
3 4
如果我對pandas.read_csv使用iterator=True
參數,則它將返回TextFileReader
/ TextParser
對象。 這樣可以動態過濾文件,並且僅選擇A
列大於2的行。
但是,如何在運行中向數據幀中添加第三列,而不必再次遍歷所有數據呢?
具體來說,我希望C
列等於A
列乘以字典d
的值,字典d
以B
列的值為鍵; 即C = A*d[B]
。
目前,我有以下代碼:
import pandas
d = {2: 2, 4: 3}
TextParser = pandas.read_csv('input.csv', sep=' ', iterator=True, comment='#')
df = pandas.concat([chunk[chunk['A'] > 2] for chunk in TextParser])
print(df)
哪個打印此輸出:
A B
1 3 4
如何獲取它以打印此輸出( C = A*d[B]
):
A B C
1 3 4 9
您可以使用生成器一次處理一個塊:
碼:
def on_the_fly(the_csv):
d = {2: 2, 4: 3}
chunked_csv = pd.read_csv(
the_csv, sep='\s+', iterator=True, comment='#')
for chunk in chunked_csv:
rows_idx = chunk['A'] > 2
chunk.loc[rows_idx, 'C'] = chunk[rows_idx].apply(
lambda x: x.A * d[x.B], axis=1)
yield chunk[rows_idx]
測試代碼:
from io import StringIO
data = StringIO(u"""#
A B
1 2
3 4
4 4
""")
import pandas as pd
df = pd.concat([c for c in on_the_fly(data)])
print(df)
結果:
A B C
1 3 4 9.0
2 4 4 12.0
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.