如何将Pandas类型的数据转换为Pandas。数据帧?

2024-10-02 00:23:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个对象的类型是熊猫和打印(对象)是给出以下输出

            print(type(recomen_total))
            print(recomen_total)

输出是

^{pr2}$

我想把这个obejct转换成pd数据帧,我怎么做?在

我试过了pd数据帧(object),他们也在抛出错误


Tags: 数据对象类型objecttype错误totalpd
2条回答

有趣的是,它不会直接转换为数据帧,而是转换为序列。一旦将其转换为序列,请使用series的to\u frame方法将其转换为DataFrame

import pandas as pd
df = pd.DataFrame({'col1': [1, 2], 'col2': [0.1, 0.2]},
                      index=['a', 'b'])

for row in df.itertuples():
    print(pd.Series(row).to_frame())

希望这有帮助!!在

编辑

如果要保存列名,请使用如下的_asdict()方法:

^{pr2}$

要从itertuples namedtuple创建新的DataFrame,也可以使用list()或Series:

import pandas as pd

# source DataFrame
df = pd.DataFrame({'a': [1,2], 'b':[3,4]})
# empty DataFrame
df_new_fromAppend = pd.DataFrame(columns=['x','y'], data=None)

for r in df.itertuples():
    # create new DataFrame from itertuples() via list() ([1:] for skipping the index):
    df_new_fromList = pd.DataFrame([list(r)[1:]], columns=['c','d'])
    # or create new DataFrame from itertuples() via Series (drop(0) to remove index, T to transpose column to row) 
    df_new_fromSeries = pd.DataFrame(pd.Series(r).drop(0)).T
    # or use append() to insert row into existing DataFrame ([1:] for skipping the index):
    df_new_fromAppend.loc[df_new_fromAppend.shape[0]] = list(r)[1:]

print('df_new_fromList:')
print(df_new_fromList, '\n')
print('df_new_fromSeries:')
print(df_new_fromSeries, '\n')
print('df_new_fromAppend:')
print(df_new_fromAppend, '\n')

输出:

^{pr2}$

要省略索引,请使用param index=False(但我主要需要迭代的索引)

for r in df.itertuples(index=False):
    # the [1:] needn't be used, for example:
    df_new_fromAppend.loc[df_new_fromAppend.shape[0]] = list(r) 

相关问题 更多 >

    热门问题