Python ValueError:无法设置没有定义索引的框架和无法转换为系列的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48306694/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 18:38:46  来源:igfitidea点击:

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

python

提问by Tanvi Mirza

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:

我在 python 3.X 中使用 Pandas 0.20.3。我想在另一个熊猫数据框中的熊猫数据框中添加一列。两个数据框都包含 51 行。所以我使用了以下代码:

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:

class_df.dtypes 给了我:

Group_ID         object
YEAR             object
Terget           object
phone            object
age              object

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

type(group['phone'])返回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:

group['phone'] 的前 5 行如下所示:

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

采纳答案by cs95

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

您有一列参差不齐的列表。您唯一的选择是分配一个列表列表,而不是一个列表数组(这是.value给出的)。

class_df['phone'] = group['phone'].tolist()

回答by Jefferson Sankara

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()

在大多数情况下,当您返回空数据帧时会出现此错误。对我有用的最佳方法是在使用 apply() 之前先检查数据框是否为空

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

回答by Essi A.

Instead of using an if-statement, you can use set result_typeargument of apply()function to "reduce".

您可以使用apply()函数的setresult_type参数来“减少” ,而不是使用 if 语句。

df['new_column'] = df.apply(func, axis=1, result_type='reduce')

回答by Thomas R

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"

“ValueError:无法设置没有定义索引的框架和无法转换为系列的值”

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

如果由于某种原因表没有任何行,也可能发生。