Home > Back-end >  How to assgin values to columns in Pandas
How to assgin values to columns in Pandas

Time:02-06

In picture it show clear i have dataframe with mentioned columns and data. Now how can i assign this data to columns.enter image description here. if you look at the picture it will be more clear.

I try differen assigning operation but it show error like shape of passed values. I expecting that data(array) value to columns

CodePudding user response:

Please refrain from adding code in the form of an image, it's hard to access. Here's an article explaining why.

Firstly, I would take the column names from the pd dataframe and put them into a list, let's call it col_names.

col_names = []
for col in df.columns:
    col_names.append(col)

Then create a new dataframe (although you can choose to modify the existing one) with the retrieved column names and the data. I have inferred that your array is stored in a variable named data.

df_updated = pd.DataFrame(data, columns = col_names)

CodePudding user response:

I assume that the problem you face is that there are many columns in the DataFrame and the Array contains values for some but not all of these columns. Hence your problem with shape when you try and combine the two. What you need to do is define the column names for the values in the data Array before combining the two. See example code below which forms another DataFrames with the correct column names and then finally joins things together.

import pandas as pd

df1 = pd.DataFrame({ 'a': [1.0, 2.0],
                    'b': [3.0, 5.0],
                    'c': [4.0, 7.0]
                    })

data = [1.1, 2.1]
names = ['a', 'b']
df2 = pd.DataFrame({key : val for key, val in zip(names, data)}, index= [0])

df3 = pd.concat([df1, df2]).reset_index(drop = True)
print(df3)

this produces

     a    b    c
0  1.0  3.0  4.0
1  2.0  5.0  7.0
2  1.1  2.1  NaN

with NaN for the columns that were missing in the data to be added. You can change the NaN to any value you want using fillna

  • Related