【问题标题】:ValueError: Cannot set a frame with no defined index and a value that cannot be converted to a SeriesValueError:无法设置没有定义索引的框架和无法转换为系列的值
【发布时间】:2022-01-11 13:30:32
【问题描述】:

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

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

我收到以下错误消息:

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

class_df.dtypes 给我:

Group_ID         object
YEAR             object
Terget           object
phone            object
age              object

而type(group['phone']) 返回pandas.core.series.Series

您能否建议我需要做哪些更改才能消除此错误?

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

【问题讨论】:

    标签: python


    【解决方案1】:

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

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

    【讨论】:

    • 解决了我的一天你是个天才
    • 另一种检查数据框是否为空的常用方法是:if not df.empty:
    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

      问题标题的错误

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

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

      【讨论】:

        【解决方案4】:

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

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

        【讨论】:

        • 对于大多数用户来说,这可能是一个更好的答案,因为您不需要 if 语句方法所需的条件块和缩进。
        【解决方案5】:

        分配给DataFrame中列的数据必须是一维数组。例如,考虑将 num_arr 添加到 DataFrame

        num_arr.shape
        

        (1, 126)

        要将此 num_arr 添加到 DataFrame column,它应该被重新整形......

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

        (126,)

        现在我可以将此 arr 设置为 DataFrame 列

        df = pd.DataFrame()
        df['numbers'] = num_arr
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-04-14
          • 1970-01-01
          • 2020-12-14
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多