Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/364.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将带有口述记录列表的熊猫系列转换为带有来自口述记录的列的数据帧_Python_Pandas_Dataframe - Fatal编程技术网

Python 将带有口述记录列表的熊猫系列转换为带有来自口述记录的列的数据帧

Python 将带有口述记录列表的熊猫系列转换为带有来自口述记录的列的数据帧,python,pandas,dataframe,Python,Pandas,Dataframe,我有一个熊猫系列,里面有一系列的录音: series = pd.Series( [[{'id': '1', 'val': 'ab'}, {'id': '2', 'val': 'abc'}], [{'id': '1', 'val': 'aa'}, {'id': '2', 'val': 'ewe'}], [{'id': '3', 'val': 'aea'}, {'id': '4', 'val': 'te'}]], index=['2014-01-01 22:59:00+00

我有一个熊猫系列,里面有一系列的录音:

series = pd.Series(
    [[{'id': '1', 'val': 'ab'}, {'id': '2', 'val': 'abc'}], [{'id': '1', 'val': 'aa'}, {'id': '2', 'val': 'ewe'}],
     [{'id': '3', 'val': 'aea'}, {'id': '4', 'val': 'te'}]],
    index=['2014-01-01 22:59:00+00:00', '2014-01-02 22:59:00+00:00', '2014-01-03 21:59:00+00:00'])
我想将其转换为具有以下列的Dataframe:

                           id   val
2014-01-01 22:59:00+00:00   1   ab
2014-01-01 22:59:00+00:00   2   abc
2014-01-02 22:59:00+00:00   1   aa
......
你知道如何实施吗? 谢谢

我尝试用不同的参数使用pandas pd.dataframe方法

df = pd.DataFrame(series)

您的示例是熊猫系列,而不是数据帧。 因此,创建一个包含两列的数据框,转换每列并重新连接数据框

df = pd.concat([sample.apply(pd.Series)[column].apply(pd.Series) for column in df.columns])
print(df.head())
输出:

                           id   val
2014-01-01 22:59:00+00:00   1   ab
2014-01-02 22:59:00+00:00   1   aa
2014-01-03 21:59:00+00:00   3   aea
2014-01-01 22:59:00+00:00   2   abc
2014-01-02 22:59:00+00:00   2   ewe
2014-01-03 21:59:00+00:00   4   te
                          id  val
2014-01-01 22:59:00+00:00  1   ab
2014-01-01 22:59:00+00:00  2  abc
2014-01-02 22:59:00+00:00  1   aa
2014-01-02 22:59:00+00:00  2  ewe
2014-01-03 21:59:00+00:00  3  aea
2014-01-03 21:59:00+00:00  4   te

您可以使用方法
explode()
(Pandas 0.25.0中新增)垂直展开表格,使用方法
apply(pd.Series)
水平展开表格:

series.explode().apply(pd.Series)
输出:

                           id   val
2014-01-01 22:59:00+00:00   1   ab
2014-01-02 22:59:00+00:00   1   aa
2014-01-03 21:59:00+00:00   3   aea
2014-01-01 22:59:00+00:00   2   abc
2014-01-02 22:59:00+00:00   2   ewe
2014-01-03 21:59:00+00:00   4   te
                          id  val
2014-01-01 22:59:00+00:00  1   ab
2014-01-01 22:59:00+00:00  2  abc
2014-01-02 22:59:00+00:00  1   aa
2014-01-02 22:59:00+00:00  2  ewe
2014-01-03 21:59:00+00:00  3  aea
2014-01-03 21:59:00+00:00  4   te

请提供一个可复制的数据样本给你。sample=pd.Series([[{'id':'1','val':'ab'},{'id':'2','val':'abc'}],{'id':'1','val':'aa'},{'id':'2','val':'ewe'}],{'id':'4','val':'te'}],索引=['2014-01-01-02 22:59:00+00:00','2014-01-02-03:00+21:00]]