运行一些命令后,我有一个pandas数据帧,例如:
>>> print df
B A
1 2 1
2 3 2
3 4 3
4 5 4
我想将其打印出来,以便生成可以重新创建它的简单代码,例如:
DataFrame([[2,1],[3,2],[4,3],[5,4]],columns=['B','A'],index=[1,2,3,4])
我尝试拉出三个部分(数据,列和行):
[[e for e in row] for row in df.iterrows()]
[c for c in df.columns]
[r for r in df.index]
但第一行失败,因为e
不是值,而是Series
。
是否有预构建命令来执行此操作,如果没有,我该如何操作?感谢。
答案 0 :(得分:1)
您可以通过调用df.values
:
df = pd.DataFrame([[2,1],[3,2],[4,3],[5,4]],columns=['B','A'],index=[1,2,3,4])
arrays = df.values
cols = df.columns
index = df.index
df2 = pd.DataFrame(arrays, columns = cols, index = index)
答案 1 :(得分:0)
基于@Woody Pride的方法,这是我正在使用的完整解决方案。它处理分层索引和索引名称。
from types import MethodType
from pandas import DataFrame, MultiIndex
def _gencmd(df, pandas_as='pd'):
"""
With this addition to DataFrame's methods, you can use:
df.command()
to get the command required to regenerate the dataframe df.
"""
if pandas_as:
pandas_as += '.'
index_cmd = df.index.__class__.__name__
if type(df.index)==MultiIndex:
index_cmd += '.from_tuples({0}, names={1})'.format([i for i in df.index], df.index.names)
else:
index_cmd += "({0}, name='{1}')".format([i for i in df.index], df.index.name)
return 'DataFrame({0}, index={1}{2}, columns={3})'.format([[xx for xx in x] for x in df.values],
pandas_as,
index_cmd,
[c for c in df.columns])
DataFrame.command = MethodType(_gencmd, None, DataFrame)
到目前为止,我只对几个案例进行了测试,并希望得到更通用的解决方案。