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)
有趣的是,它不会直接转换为数据帧,而是转换为序列。一旦将其转换为序列,请使用series的to\u frame方法将其转换为DataFrame
希望这有帮助!!在
编辑
如果要保存列名,请使用如下的_asdict()方法:
^{pr2}$要从itertuples namedtuple创建新的DataFrame,也可以使用list()或Series:
输出:
^{pr2}$要省略索引,请使用param index=False(但我主要需要迭代的索引)
相关问题 更多 >
编程相关推荐