DEV Community

Punitha
Punitha

Posted on

String Operations

  • Pandas provides string functions using .str.

Convert to lowercase

df["Name"] = df["Name"].str.lower()
Enter fullscreen mode Exit fullscreen mode

Convert to uppercase

df["Name"] = df["Name"].str.upper()
Enter fullscreen mode Exit fullscreen mode

Remove extra spaces

df["Name"] = df["Name"].str.strip()
Enter fullscreen mode Exit fullscreen mode

Search text

result = df[df["Name"].str.contains("Arun")]
Enter fullscreen mode Exit fullscreen mode

GroupBy

  • groupby() is one of the most important Pandas functions for data analysis.

  • It groups data based on a column.

result = df.groupby("Grade")["Marks"].mean()

print(result)
Enter fullscreen mode Exit fullscreen mode

Aggregation

  • We can use multiple calculations with agg(), min() and max().
result = df["Marks"].agg(
    ["mean", "min", "max"]
)

print(result)
Enter fullscreen mode Exit fullscreen mode

Combining Data with concat()

  • concat() is used to combine DataFrames.
df1 = pd.DataFrame({
    "Name": ["Arun", "Priya"]
})

df2 = pd.DataFrame({
    "Name": ["Ravi", "Kumar"]
})

result = pd.concat([df1, df2])

print(result)
Enter fullscreen mode Exit fullscreen mode

Combining Data with merge()

  • merge() is similar to a SQL JOIN.
result = pd.merge(
    students,
    marks,
    on="Student_ID"
)

print(result)
Enter fullscreen mode Exit fullscreen mode

join()

  • join() can also be used to combine DataFrames, commonly based on their indexes.
result = df1.join(df2)
Enter fullscreen mode Exit fullscreen mode

Pivot Table

  • A pivot table is used to summarize data.
result = pd.pivot_table(
    df,
    values="Marks",
    index="Grade",
    aggfunc="mean"
)

print(result)
Enter fullscreen mode Exit fullscreen mode

Apply Function

  • apply() is used to apply a function to DataFrame values.
df["Marks"] = df["Marks"].apply(lambda x: x + 5)
Enter fullscreen mode Exit fullscreen mode

Top comments (0)