numpy 动态创建pandas Dataframe

2fjabf4q  于 2023-04-12  发布在  其他
关注(0)|答案(1)|浏览(103)

我想做一个pandas数据框,每一列都有特定数量的值。它将有四列:GenderRoleRegion和一个名为Survey的指示符变量。这些列的可能值分别为1-3、1-4、1-6和1或0。
我希望有11,725行,每列中每个值都有特定的数字(例如对于Gender为261 × 1 m4n1x,其中Survey1,对于Role为2,392 × 1 m8n1x,其中Survey0,等等)。我如何设置 Dataframe 以精确地拥有我想要的某些值的数量?这将基于Word中的此表,这里我基本上是旋转Characteristics列,然后得到行数,因为这里每个单元格中都有值。我确信我可以使用numpy来实现这一点,但我不确定具体如何实现。

1yjd4xko

1yjd4xko1#

您可以使用numpy.repeat()函数生成一个重复值数组,然后使用pd.concat()将它们连接到Pandas Dataframe 中。下面是一个示例代码片段,应该可以实现您想要的功能:

import numpy as np
import pandas as pd

# Define the possible values for each column
gender_values = [1, 2, 3]
role_values = [1, 2, 3, 4]
region_values = [1, 2, 3, 4, 5, 6]
survey_values = [0, 1]

# Define the number of occurrences for each value in each column
gender_counts = [261, 3872, 7592]
role_counts = [2358, 2392, 3540, 3535]
region_counts = [1641, 2092, 1936, 1447, 1394, 2215]
survey_counts = [6000, 5725]

# Generate the arrays of repeated values for each column
gender = np.repeat(gender_values, gender_counts)
role = np.repeat(role_values, role_counts)
region = np.repeat(region_values, region_counts)
survey = np.repeat(survey_values, survey_counts)

# Combine the arrays into a Pandas dataframe
df = pd.concat([pd.Series(gender), pd.Series(role), pd.Series(region), pd.Series(survey)], axis=1)
df.columns = ['Gender', 'Role', 'Region', 'Survey']

# Print the resulting dataframe
print(df)

这段代码应该生成一个Pandas数据框,其中有11,725行,每列中的每个值都有指定的出现次数。

相关问题