简体   繁体   English

在循环中添加多个列并在 Python 中创建 Dataframe

[英]Adding multiple column in a Loop and creating a Dataframe in Python

Here I am trying to create a data frame with multiple columns.在这里,我试图创建一个具有多列的数据框。 I have 760 names and I want to create a column for each name and then altogether they will form a data frame with the names in the top and the product values in the corresponding column of each product name.我有 760 个名称,我想为每个名称创建一个列,然后它们将形成一个数据框,名称位于顶部,产品值位于每个产品名称的相应列中。 I get the result as I want.我得到了我想要的结果。 But the problem what occurs is, after running the function and the loop the result which is returned is the column of the last name in the array.但出现的问题是,在运行 function 和循环后,返回的结果是数组中姓氏的列。 Where I am stuck is how to save the name of the product while running the loop in the data frame so that at the end i will have the data frame with all the product information.我被卡住的地方是如何在数据框中运行循环时保存产品名称,以便最后我将拥有包含所有产品信息的数据框。 Thanks in advance!提前致谢!

`dfPN1 = ['BSP752R', 'BTS6143D']
 P = []
 x = []
def f(y):
    P = 0
    P2 = []
    for x in y:
        df_PL_test = df[(df['PL'] == 27)&(df['Diff Load Due Week'] == -1)& (df['Product Name']      == x)]
    
        df_PL_test_sum = df_PL_test.groupby('Delivery_Week_Due' ,as_index =False)['BillingsAndBacklogs'].sum()
    
        df_PL_test_sum_norm = preprocessing.normalize(df_PL_test_sum, axis = 0)
 
        df_test_scaled = pd.DataFrame(df_PL_test_sum_norm, columns = df_PL_test_sum.columns)
    
        P = np.array(df_test_scaled.BillingsAndBacklogs)
    
        a_dataframe = pd.DataFrame({x: P})
    
   return a_dataframe`

Given a df that looks like: dfp =给定一个看起来像这样的df:dfp =

    Name    Prod
0   Tom     A
1   Bob     B
2   Tom     B
3   Bill    C
4   Sally   B
5   Bob     C  

You can run:你可以运行:

dfp = dfp.pivot(columns= 'Name')  
dfp = dfp.replace(np.nan, '')
dfp = dfp.pivot(columns= 'Name')  

which yields:产生:

    Prod
Name    Bill    Bob Sally   Tom
0                            A
1                B      
2                            B
3        C          
4                      B    
5                 C     

Which seems to be the desired result.这似乎是预期的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM