ValueError: Cannot set a frame with no defined index and a value that cannot be converted to a Series

Question:

I’m using Pandas 0.20.3 in my python 3.X. I want to add one column in a pandas data frame from another pandas data frame. Both the data frame contains 51 rows. So I used following code:

class_df['phone']=group['phone'].values

I got following error message:

ValueError: Cannot set a frame with no defined index and a value that cannot be converted to a Series

class_df.dtypes gives me:

Group_ID         object
YEAR             object
Terget           object
phone            object
age              object

and type(group['phone']) returns pandas.core.series.Series

Can you suggest me what changes I need to do to remove this error?

The first 5 rows of group[‘phone’] are given below:

0    [735015372, 72151508105, 7217511580, 721150431...
1                                                   []
2    [735152771, 7351515043, 7115380870, 7115427...
3    [7111332015, 73140214, 737443075, 7110815115...
4    [718218718, 718221342, 73551401, 71811507...
Name: phoen, dtype: object
Asked By: Tanvi Mirza

||

Answers:

You have a column of ragged lists. Your only option is to assign a list of lists, and not an array of lists (which is what .value gives).

class_df['phone'] = group['phone'].tolist()
Answered By: cs95

In most cases, this error comes when you return an empty dataframe. The best approach that worked for me was to check if the dataframe is empty first before using apply()

if len(df) !=  0:
    df['indicator'] = df.apply(assign_indicator, axis=1)
Answered By: Jefferson Sankara

Instead of using an if-statement, you can use set result_type argument of apply() function to “reduce”.

df['new_column'] = df.apply(func, axis=1, result_type='reduce')
Answered By: Essi A.

The error of the Question-Headline

“ValueError: Cannot set a frame with no defined index and a value that cannot be converted to a Series”

might as well occur if for what ever reason the table does not have any rows.

Answered By: Thomas R

The data assigned to a column in the DataFrame must be a single dimension array. For example, consider a num_arr to be added to a DataFrame

num_arr.shape

(1, 126)

For this num_arr to be added to a DataFrame column, It should be reshaped….

num_arr = num_arr.reshape(-1, )
num_arr.shape

(126,)

Now I could set this arr as a DataFrame column

df = pd.DataFrame()
df['numbers'] = num_arr
Answered By: Hemanth Kollipara
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.