Skip to main content
 首页 » 编程设计

Python 数据帧复制

2024年10月01日7mq0036

我正在尝试根据基于原始数据框的某些标准创建新数据框。

df = pandas.io.sql.read_sql(sql, conn) 
 
Count_Row = df.shape[0] 
for j in range(Count_Row - 1): 
 
    if df.iloc[j, 0] == df.iloc[j + 1, 0]: 
        print(df.iloc[j, 2] + df.iloc[j + 1, 2], df.iloc[j, 4], df.iloc[j, 6], df.iloc[j, 3]) 

然而,我不想打印,而是想将该数据添加到新的数据框中。

这怎么可能?

请您参考如下方法:

您可以将其附加到新的数据框,而不是打印出数据

import pandas as pd 
 
df = pandas.io.sql.read_sql(sql, conn) 
Count_Row = df.shape[0] 
 
results = pd.DataFrame() # create data frame to store results 
 
for j in range(Count_Row - 1): 
    if df.iloc[j, 0] == df.iloc[j + 1, 0]: 
        # create row of values to append 
        row = pd.Series([df.iloc[j, 2] + df.iloc[j + 1, 2],  
                        df.iloc[j, 4],  
                        df.iloc[j, 6],  
                        df.iloc[j, 3]]) 
        results = results.append([row]) 
 
results.columns = ['v1', 'v2', 'v3', 'v4'] # the variables 

这将为您提供具有所需输出的数据框