如何将DataFrame列收集到python中的键值对中 [英] how to gather DataFrame column into key value pairs as row in python

查看:637
本文介绍了如何将DataFrame列收集到python中的键值对中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将一个大熊猫DataFrame列收集到一个键值中,将列表列为python中的一行。如果我们以DataFrame为例,我想从这里开始:

I'm trying gather a pandas DataFrame column into a key value pairs an list it as a row in python. If we take this DataFrame as example, I want to go from here:

import pandas as pd
from collections import OrderedDict

df = pd.DataFrame({'value_2016': [200],
                   'value_2017': [300],
                   'value_2018': [float('NaN')]})
print(df)

     value_2016  value_2017  value_2018
0         200         300         NaN

to:

df_result = pd.DataFrame(OrderedDict({'year': [2016, 2017],
                                      'value': [200, 300]}))

print(df_result)

   year  value
0  2016    200
1  2017    300

如果您对R熟悉,那么相当于此:

If you are familiar in R the equivalent would be something like this:

require("plyr"); require("dplyr"); require(tidyr)

df <- data.frame(value_2016 = 200,
                 value_2017 = 300,
                 value_2018 = NA)

df %>% 
   gather(year, value, value_2016:value_2018) %>% 
   mutate(year = gsub(x = .$year, replacement = "", "value_")) %>% 
   na.exclude

     year value
   1 2016   200
   2 2017   300

任何帮助都会非常好!

推荐答案

您可以创建 MultiIndex split ,然后通过 stack

You can create MultiIndex by split and then reshape by stack:

df.columns = df.columns.str.split('_', expand=True)
df = df.stack().reset_index(level=0, drop=True).rename_axis('year').reset_index()
#if necessary convert float to int
df.value = df.value.astype(int)
print (df)
   year  value
0  2016    200
1  2017    300

如果要使用 DataFrame 构造方法使用 get_level_values

If want use DataFrame constructor use get_level_values:

df.columns = df.columns.str.split('_', expand=True)
df = df.stack()

df_result = pd.DataFrame(OrderedDict({'year': df.index.get_level_values(1),
                                      'value': df['value'].astype(int).values}))

print(df_result)
   year  value
0  2016    200
1  2017    300

这篇关于如何将DataFrame列收集到python中的键值对中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆