Answers for "add a column with a data type to panda"

43

how to add a column to a pandas df

#using the insert function:
df.insert(location, column_name, list_of_values) 
#example
df.insert(0, 'new_column', ['a','b','c'])
#explanation:
#put "new_column" as first column of the dataframe
#and puts 'a','b' and 'c' as values

#using array-like access:
df['new_column_name'] = value

#df stands for dataframe
Posted by: Guest on March-18-2020
2

Adding new column to existing DataFrame in Pandas using assign method

# import pandas library
import pandas as pd

# create pandas DataFrame
df = pd.DataFrame({'team': ['India', 'South Africa', 'New Zealand', 'England'],
                   'points': [10, 8, 3, 5],
                   'runrate': [0.5, 1.4, 2, -0.6],
                   'wins': [5, 4, 2, 2]})

# print the DataFrame
print(df)

# append multiple columns to Pandas DataFrame
df2 = df.assign(lost=[2, 1, 3, 4], matches_remaining=[2, 3, 1, 1])

# Print the new DataFrame
print(df2)
Posted by: Guest on January-24-2022

Code answers related to "add a column with a data type to panda"

Python Answers by Framework

Browse Popular Code Answers by Language