【问题标题】:Convert dataframe to tuple and then back into dataframe in Python Pandas将数据框转换为元组,然后在 Python Pandas 中转换回数据框
【发布时间】:2017-02-19 03:47:04
【问题描述】:

我希望使用以下方法从元组列表中获取数据帧:

tuples = tuple(df.itertuples(index=False))
#do some code, passing out df
ls = [(tup._fields, pd.Series(tup).to_frame()) for tup in tuples]

获取命名元组的方法是 tup._fields。

我想按原样重新创建数据框,但我不能这样做 pythonic-ly。

如何将此列表合并为一个完整的数据框,并以 tup._fields 作为列标题?

我试过了:

ls = [pd.Series(tup).loc[0] for tup in tuples]
df=pd.DataFrame({tup._fields: ls})

这假设我在变量 tup 中只有一行系列,但这不适用于更大的 dfs。

【问题讨论】:

  • 在文档 tup._fields 中找到了这个,所以修改原始问题。

标签: python-3.x pandas


【解决方案1】:

为什么要提取tup._fields 行?您可以使用NamedTuple 列表转换回来。

考虑这个例子:

df = pd.DataFrame({'one' : pd.Series([1., 2., 3.], index=['a', 'b', 'c']),
       'two' : pd.Series([1., 2., 3., 4.], index=['a', 'b', 'c', 'd'])})

tuples = tuple(df.itertuples(index=False))

df2 = pd.DataFrame(list(tuples))

df2.head()

#>    one  two
#> 0  1.0  1.0
#> 1  2.0  2.0
#> 2  3.0  3.0
#> 3  NaN  4.0

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-17
    • 2014-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-20
    相关资源
    最近更新 更多