Tutorial by Examples

There are a couple of ways to delete a column in a DataFrame. import numpy as np import pandas as pd np.random.seed(0) pd.DataFrame(np.random.randn(5, 6), columns=list('ABCDEF')) print(df) # Output: # A B C D E F # 0 -0.895467 0.386902...
df = pd.DataFrame({'old_name_1': [1, 2, 3], 'old_name_2': [5, 6, 7]}) print(df) # Output: # old_name_1 old_name_2 # 0 1 5 # 1 2 6 # 2 3 7 To rename one or more columns, pass the old names and new names as a dictionary: df.r...
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]}) print(df) # Output: # A B # 0 1 4 # 1 2 5 # 2 3 6 Directly assign df['C'] = [7, 8, 9] print(df) # Output: # A B C # 0 1 4 7 # 1 2 5 8 # 2 3 6 9 Add a constant column df['C'] = 1 print(df) # Ou...
import pandas as pd df = pd.DataFrame({'gender': ["male", "female","female"], 'id': [1, 2, 3] }) >>> df gender id 0 male 1 1 female 2 2 female 3 To encode the male to 0 and female to 1: df.loc[df["gender&quot...
Given a DataFrame: s1 = pd.Series([1,2,3]) s2 = pd.Series(['a','b','c']) df = pd.DataFrame([list(s1), list(s2)], columns = ["C1", "C2", "C3"]) print df Output: C1 C2 C3 0 1 2 3 1 a b c Lets add a new row, [10,11,12]: df = pd.DataFrame(np.array(...
let's generate a DataFrame first: df = pd.DataFrame(np.arange(10).reshape(5,2), columns=list('ab')) print(df) # Output: # a b # 0 0 1 # 1 2 3 # 2 4 5 # 3 6 7 # 4 8 9 drop rows with indexes: 0 and 4 using drop([...], inplace=True) method: df.drop([0,4], inplace=True) ...
# get a list of columns cols = list(df) # move the column to head of list using index, pop and insert cols.insert(0, cols.pop(cols.index('listing'))) # use ix to reorder df2 = df.ix[:, cols]

Page 1 of 1