python - 来自嵌套元组的 Pandas Dataframe

标签 python pandas dataframe tuples

我有一些数据看起来有点像这样:

    data=[([('thing1',
    'thing1a'),
   ('thing1',
    'thing1b'),
   ('thing1',
    'thing1c'),
   ('thing1',
    'thing1d'),
   ('thing1',
    'thing1e')],
  'thing1description'),
 ([('thing2',
    'thing2a')],
  'thing2description'),
 ([('thing3',
 'thing3a')],
 'thing3description')]

我想构建一个如下所示的数据框:

thing_number    thing_letter    description
thing1            thing1a   thing1description
thing1            thing1b   thing1description
thing1            thing1c   thing1description
thing1            thing1d   thing1description
thing1            thing1e   thing1description
thing2            thing2a   thing2description
thing3            thing3a   thing3description

感谢之前的一个非常类似的问题,例如 this我可以使用下面的方法来实现它,但我认为我必须遗漏一些东西才能使其更加优雅:

data_=pd.DataFrame(data,columns=['thing','description'])
data_=data_.explode('thing')
data_=pd.concat([data_,pd.DataFrame([(*i, k) for k,j in data for i in k], columns=['thing_number','thing_letter','all'],index=data_.index)],axis=1)
data_=data_[['thing_number','thing_letter','description']]

总而言之,我正在寻找一种更有效、更优雅的方式来解除元组列表的嵌套。提前致谢。

最佳答案

基于相同方法的较短代码:

df = (pd.DataFrame(data, columns=['thing','description'])
        .explode('thing',
                 ignore_index=True) # optional
       )

df[['thing_number','thing_letter']] = df.pop('thing').tolist()

输出:

         description thing_number thing_letter
0  thing1description       thing1      thing1a
1  thing1description       thing1      thing1b
2  thing1description       thing1      thing1c
3  thing1description       thing1      thing1d
4  thing1description       thing1      thing1e
5  thing2description       thing2      thing2a
6  thing3description       thing3      thing3a

关于python - 来自嵌套元组的 Pandas Dataframe,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73956945/

相关文章:

python - 如何旋转 x 标签或 y 标签? (hvplot 或全息图)

python - 关于add_scalar()的TensorboardX输入问题

python - 扭曲的 Web 客户端可以通过 SOCKS 代理发出请求吗?

python - 将条件 if/else 逻辑与 pandas 数据框列一起使用

r - 选择具有特定条件的子数据集,而不使用应用和子集函数

python - numpy 开始、精确、收敛结束

python - 使用 pd.read_csv 时跳过日期不正确的行

python - 数据透视表中的条形图,包含总计和每组聚合的百分比

python - 设置列 dtypes pandas python 时遇到问题

pandas - 有什么方法可以更改数据框的索引以进行绘图吗?