【问题标题】:Convert tabular pandas DataFrame into nested pandas DataFrame将表格 pandas DataFrame 转换为嵌套的 pandas DataFrame
【发布时间】:2021-05-26 11:46:57
【问题描述】:

假设我有一个像这样的简单 pd.DataFrame:


d = {'col1': [1, 20], 'col2': [3, 40], 'col3': [5, 50]}

df = pd.DataFrame(data=d)


df
   col1  col2  col4
0     1     3     5
1    20    40    60

有没有办法将其转换为 nasted pandas Dataframe (df_new) ,例如当我调用 df_new.values[0] 时将其作为输出:

array(
[0    1
 1    3
 2    5
Length: 3, dtype: int], dtype=object)

【问题讨论】:

  • 这个 [0 1 1 3] 数组到底是什么?
  • 所以,感谢您的反馈! 0 和 1 是索引,1 和 3 是第一行的值!我现在要更新我的问题!谢谢
  • 嗯...所以你想为索引1返回值3
  • 抱歉造成误会。我想将此数据框转换为另一个,当我调用此命令(df_new.values [0])时,将其作为输出!
  • 那么第二行的预期数组是什么(0 20、1 40、2 60)?

标签: pandas dataframe object nested tabular


【解决方案1】:

我仍然不认为我理解确切的要求,但这里有一些东西:

获得所需output 的一种方法是:

>>> pd.Series(df.T[0].values)

0    1
1    3
2    5
dtype: int64

如果您想将这些作为二维数组:

>>> np.array(pd.DataFrame(df.T[0].values).reset_index())

array([[0, 1],
       [1, 3],
       [2, 5]])

>>> np.array(pd.DataFrame(df.T[1].values).reset_index())

array([[ 0, 20],
       [ 1, 40],
       [ 2, 50]])

【讨论】:

  • 非常感谢,但输出格式不正确。我不确切知道“df_new.values[0]”是什么类型,但我认为它类似于 pd.Series!
  • 你是怎么得到object的?你能否详细说明你想用这个实现什么......我的意思是,一旦你有了这些数据 - 你会用这个做什么?另外,你用什么命令来提取你的object
  • 感谢您的宝贵时间。这次我会尽力为你解释得更好。因此,在此链接中:github.com/alan-turing-institute/sktime/blob/main/examples/…,在单元格 [3] 中,数据帧以“奇怪”的形式读取,如您所见。然后在 Cell [6] 中转换为另一种形式。我的问题是,假设我们有一个数据框(如在 Cell[6] 中),我们如何将其转换为数据框形式(如在 Cell[3] 中)?
猜你喜欢
  • 2019-06-09
  • 2014-06-27
  • 1970-01-01
  • 2021-12-29
  • 2013-11-16
  • 2019-04-08
  • 2023-02-10
  • 2018-10-26
相关资源
最近更新 更多