【问题标题】:Faker and Pandas | ValueError: Length of values (1) does not match length of index (2)Faker 和熊猫 | ValueError:值的长度 (1) 与索引的长度 (2) 不匹配
【发布时间】:2021-08-22 13:45:11
【问题描述】:

我正在使用 Faker;用于为您的模拟数据集生成值的库。

我正在使用 Jupyter 笔记本

此代码的目标是在性别条件下生成特定的假数据。例如。比如“夫人”和“彼得”不要混在一起。

错误与我如何将数据附加到数据框有关。

单元格 1:

import numpy as np
import pandas as pd

from faker import Faker
fake = Faker()

import random

np.random.seed(42)

单元格 2:

def example_dataset_simulation(samples, cols):
    df = pd.DataFrame(index=np.arange(samples), columns=np.arange(cols))
    
    #for col in range(cols):
    for row in range(samples):       
        gender = random.randint(0, 1)
        
        df['Prefix'] = [fake.prefix_male() if gender == 0 else fake.prefix_female()]
        df['Forename'] = [fake.first_name_male() if gender == 0 else fake.prefix_female()]
        df['Surname'] = fake.first_name()  # unconditional
        df['Suffix'] = [fake.suffix_male() if gender == 0 else fake.suffix_female()]
    
    return df

单元格 3:

df = example_dataset_simulation(2, 2)
df

错误:

ValueError: Length of values (1) does not match length of index (2)

【问题讨论】:

    标签: python pandas dataframe jupyter faker


    【解决方案1】:

    我的 if-conditional “输出” 周围不能有 list notation

    即删除 '[]':

    原文:

    df['Prefix'] = [fake.prefix_male() if gender == 0 else fake.prefix_female()]
    

    现在:

    df['Prefix'] = fake.prefix_male() if gender == 0 else fake.prefix_female()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-30
      • 1970-01-01
      • 1970-01-01
      • 2021-10-23
      • 2018-12-19
      • 2022-01-13
      相关资源
      最近更新 更多