Create Pandas DataFrames from Unique Values in one Column

后端 未结 3 1222
难免孤独
难免孤独 2020-12-16 08:18

I have a Pandas dataframe with 1000s of rows. and it has the Names column includes the customer names and their records. I want to create individual dataframes

3条回答
  •  清酒与你
    2020-12-16 09:05

    maybe i get you wrong but

    when

    for x in customerNames:
        x = DataFrame.loc[DataFrame['customer name'] == x]
    x
    

    gives you the right output for the last list entry its because your output is out of the indent of the loop

    import pandas as pd
    
    customer_df = pd.DataFrame.from_items([('A', ['Jean', 'France']), ('B', ['James', 'USA'])],
                            orient='index', columns=['customer', 'country'])
    
    customer_list = ['James', 'Jean']
    
    for x in customer_list:
        x = customer_df.loc[customer_df['customer'] == x]
        print(x)
        print('now I could append the data to something new')
    

    you get the output:

      customer country
    B    James     USA
    now I could append the data to something new
      customer country
    A     Jean  France
    now I could append the data to something new
    

    Or if you dont like loops you could go with

    import pandas as pd
    
    customer_df = pd.DataFrame.from_items([('A', ['Jean', 'France']), ('B', ['James', 'USA']),('C', ['Hans', 'Germany'])],
                            orient='index', columns=['customer', 'country'])
    
    customer_list = ['James', 'Jean']
    
    
    print(customer_df[customer_df['customer'].isin(customer_list)])
    

    Output:

      customer country
    A     Jean  France
    B    James     USA
    

    df.isin is better explained under:How to implement 'in' and 'not in' for Pandas dataframe

提交回复
热议问题