Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
231 views
in Technique[技术] by (71.8m points)

python - How can I convert 2d to 1d array with df.apply (lambda) in Pandas? Tooked some errors

I have a function that converts a 2 dimensional array into a one dimensional array.

def twoone(list1):
    list2 = []
    a = ""
    for x in range(len(list1)):
        for y in range(len(list1[1])):
            list1
            if list1[0][0] == list1[x][y]:
              a+=""+str(list1[x][y])  
            elif list1[1][0] == list1[x][y]:
              a+=""+str(list1[x][y])  
            else:
              a+=" "+str(list1[x][y])
            
        list2.append(a)
        a = ""
    return list2

data.csv is as follows:

Make,Model,Year,Engine Fuel Type,Engine HP,Engine Cylinders,Transmission Type,Driven_Wheels,Number of Doors,Market Category,Vehicle Size,Vehicle Style,highway MPG,city mpg,Popularity,MSRP
BMW,1 Series M,2011,premium unleaded (required),335,6,MANUAL,rear wheel drive,2,Factory Tuner,Luxury,High-Performance,Compact,Coupe,26,19,3916,46135
BMW,1 Series,2011,premium unleaded (required),300,6,MANUAL,rear wheel drive,2,Luxury,Performance,Compact,Convertible,28,19,3916,40650
BMW,1 Series,2011,premium unleaded (required),300,6,MANUAL,rear wheel drive,2,Luxury,High-Performance,Compact,Coupe,28,20,3916,36350
BMW,1 Series,2011,premium unleaded (required),230,6,MANUAL,rear wheel drive,2,Luxury,Performance,Compact,Coupe,28,18,3916,29450
BMW,1 Series,2011,premium unleaded (required),230,6,MANUAL,rear wheel drive,2,Luxury,Compact,Convertible,28,18,3916,34500
BMW,1 Series,2012,premium unleaded (required),230,6,MANUAL,rear wheel drive,2,Luxury,Performance,Compact,Coupe,28,18,3916,31200

dataframe looks like below:

X = [['200', 2017, 'flex fuel (unleaded/E85)', 184, 4, 'AUTOMATIC',
        'front wheel drive', 4, 'Flex Fuel', 'Midsize', 'Sedan', '36',
        '23', 1013, 22490, nan, nan],
     ['100', 1993, 'regular unleaded', 172, 6, 'MANUAL',
        'front wheel drive', 4, 'Luxury', 'Midsize', 'Sedan', '24', '17',
        3105, 2000, nan, nan]]

I want to add another column into the dataframe, using df.apply

When I use follow code:

df['context'] = df.apply(twoone(X), axis=1) 

I get this error

SpecificationError: Function names must be unique if there is no new column names assigned

And using this style : df['context'] = df.apply(twoone, axis=1)

I get this error

TypeError: 'int' object is not subscriptable

Samples that generally using lambda...

How can we create lambda or solve this problem?

Thanks a lot.

question from:https://stackoverflow.com/questions/65917441/how-can-i-convert-2d-to-1d-array-with-df-apply-lambda-in-pandas-tooked-some-e

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

So, you can do that like so:

>>> import pandas as pd

>>> df = pd.read_csv("sample.txt")
>>> df
                Make                        Model  Year  Engine Fuel Type Engine HP  Engine Cylinders  ...  Vehicle Size Vehicle Style highway MPG city mpg Popularity     MSRP
BMW 1 Series M  2011  premium unleaded (required)   335                 6    MANUAL  rear wheel drive  ...       Compact         Coupe          26       19     3916.0  46135.0
    1 Series    2011  premium unleaded (required)   300                 6    MANUAL  rear wheel drive  ...   Convertible            28          19     3916    40650.0      NaN
    1 Series    2011  premium unleaded (required)   300                 6    MANUAL  rear wheel drive  ...         Coupe            28          20     3916    36350.0      NaN
    1 Series    2011  premium unleaded (required)   230                 6    MANUAL  rear wheel drive  ...         Coupe            28          18     3916    29450.0      NaN
    1 Series    2011  premium unleaded (required)   230                 6    MANUAL  rear wheel drive  ...            28            18        3916    34500        NaN      NaN
    1 Series    2012  premium unleaded (required)   230                 6    MANUAL  rear wheel drive  ...         Coupe            28          18     3916    31200.0      NaN

[6 rows x 16 columns]

>>> df['context'] = df.apply(lambda x: " ".join(map(str, x.values.tolist())), axis=1) 
>>> df
                Make                        Model  Year  Engine Fuel Type Engine HP  ... highway MPG  city mpg Popularity     MSRP                                            context
BMW 1 Series M  2011  premium unleaded (required)   335                 6    MANUAL  ...          26        19     3916.0  46135.0  2011 premium unleaded (required) 335 6 MANUAL ...
    1 Series    2011  premium unleaded (required)   300                 6    MANUAL  ...          19      3916    40650.0      NaN  2011 premium unleaded (required) 300 6 MANUAL ...
    1 Series    2011  premium unleaded (required)   300                 6    MANUAL  ...          20      3916    36350.0      NaN  2011 premium unleaded (required) 300 6 MANUAL ...
    1 Series    2011  premium unleaded (required)   230                 6    MANUAL  ...          18      3916    29450.0      NaN  2011 premium unleaded (required) 230 6 MANUAL ...
    1 Series    2011  premium unleaded (required)   230                 6    MANUAL  ...        3916     34500        NaN      NaN  2011 premium unleaded (required) 230 6 MANUAL ...
    1 Series    2012  premium unleaded (required)   230                 6    MANUAL  ...          18      3916    31200.0      NaN  2012 premium unleaded (required) 230 6 MANUAL ...

[6 rows x 17 columns]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...