Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

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, '
')
print('df_new_fromSeries:')
print(df_new_fromSeries, '
')
print('df_new_fromAppend:')
print(df_new_fromAppend, '
')
Comment

PREVIOUS NEXT
Code Example
Python :: wx.SingleInstanceCheckerindexmodules 
Python :: simplejwt in django setup 
Python :: grepper how to use fraction 
Python :: anvil get last row of data table 
Python :: createdb psql 
Python :: convert an image to matrix in python 
Python :: num = [7,8, 120, 25, 44, 20, 27] newnum = [] def remove_even(num): for i in num: if i%2 != 0: newnum.append(i) return newnum print("get_unevens") test(remove_even(num), [7,25,27]) 
Python :: print e 
Python :: python range function 
Python :: intersection of list of sets 
Python :: python merge two byte files 
Python :: python types generator 
Python :: how to put 2 code n 1 line in python 
Python :: Pouring 8 litres into 2 empty container of size 3 and 5 to get 4 litre in any container 
Python :: same quotes in a quotes 
Python :: write a python program which accepts the user 
Python :: python open file partially 
Python :: count wit for loop pthoon 
Python :: python attributes from string 
Python :: fine tune huggingface model pytorch 
Python :: multiplication table for number python codewars 
Python :: c to python translator 
Python :: get size of file python 
Python :: odd and even python 
Python :: dice rolling simulator python code 
Python :: python bytes to hex 
Python :: true in python 
Python :: Python If ... Else 
Python :: python range of array 
Python :: python dunder methods 
ADD CONTENT
Topic
Content
Source link
Name
2+7 =