python - 根据特定条件将数据帧一列中的所有行转置为多列

标签 python python-3.x pandas dataframe transpose

我想根据某些值/条件将数据框中的一列数据转换为多列。

请找到生成输入数据帧的代码

df1 = pd.DataFrame({'VARIABLE':['studyid',1,'age_interview', 65,'Gender','1.Male',
                            '2.Female',
                            'Ethnicity','1.Chinese','2.Indian','3.Malay']})

数据如下所示

enter image description here

请注意,我可能事先不知道列名称。但它通常遵循这种格式。我上面显示的是示例数据,实际数据可能有大约 600-700 列,并且数据以这种方式排列

我想做的是以非数字(字符)开头的值转换为数据框中的新列。它可以是一个新的数据框。

我尝试编写一个 for 循环,但由于以下错误而失败。您能帮我实现这个结果吗?

for i in range(3,len(df1)):
#str(df1['VARIABLE'][i].contains('^\d'))
    if (df1['VARIABLE'][i].astype(str).contains('^\d') == True):

通过上面的循环,我试图检查第一个字符是否是数字,如果是,则将其保留为值(例如:1,2,3等),如果它是字符(例如:性别,种族等),然后创建一个新列。但我猜这是一个不正确且冗长的方法

例如,在上面的示例中,列将为 Studyid、age_interview、Gender、Ethnicity。

最终输出如下

enter image description here

您能否告诉我是否有一种优雅的方法可以做到这一点?

最佳答案

您可以使用 groupby 执行以下操作:

m=~df1['VARIABLE'].str[0].str.isdigit().fillna(True)
new_df=(pd.DataFrame(df1.groupby(m.cumsum()).VARIABLE.apply(list).
                                    values.tolist()).set_index(0).T)
print(new_df.rename_axis(None,axis=1))

  studyid age_interview    Gender  Ethnicity
1       1            65    1.Male  1.Chinese
2    None          None  2.Female   2.Indian
3    None          None      None    3.Malay

说明:m是一个辅助系列,有助于分隔组:

print(m.cumsum())
0     1
1     1
2     2
3     2
4     3
5     3
6     3
7     4
8     4
9     4
10    4

然后我们将这个助手系列分组并应用列表:

df1.groupby(m.cumsum()).VARIABLE.apply(list)
VARIABLE
1                                 [studyid, 1]
2                          [age_interview, 65]
3                   [Gender, 1.Male, 2.Female]
4    [Ethnicity, 1.Chinese, 2.Indian, 3.Malay]
Name: VARIABLE, dtype: object

此时,我们将每个组作为一个列表,其中列名称作为第一个条目。 因此,我们用它创建一个数据框,并将第一列设置为索引并转置以获得我们想要的输出。

关于python - 根据特定条件将数据帧一列中的所有行转置为多列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56371432/

相关文章:

python - 为什么即使没有执行/'x' 权限也可以运行 python 脚本?

python - 为什么在下面的代码示例中, 'c' 在其他任何内容之前打印?

python - 无法从 AWS Lambda 上的 Scrapy 获取结果

python - df.fillna(df.mean()) 无法按预期工作

Python 在时间序列数据框中填充零并保留现有值

Python + Pygame; screen.fill() 崩溃窗口

python [SSL] PEM 库 (_ssl.c :3309) error when verifying certificate

python - 当我运行 `for glyph in font.iter(' glyph')` 时,为什么 etree 没有从我的 SVG 中返回任何内容?

python - 在Python中修改特定索引处的多维数组

python - 使用列表制作 pandas df