📜  从 itertuples 创建一个新的 DataFrame,namedtuple 使用系列或 list() - Python 代码示例

📅  最后修改于: 2022-03-11 14:46:37.578000             🧑  作者: Mango

代码示例1
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')