Answers for "creating a new DataFrame from itertuples, namedtuple using a series or list()"

0

creating a new DataFrame from itertuples, namedtuple using a series or list()

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')
Posted by: Guest on September-29-2021

Code answers related to "creating a new DataFrame from itertuples, namedtuple using a series or list()"

Python Answers by Framework

Browse Popular Code Answers by Language