Write a program in Python to store the city and state names that start with ‘k’ in a given DataFrame into a new CSV file


Input

Assume, we have DataFrame with City and State columns and find the city, state name startswith ‘k’ and store into another CSV file as shown below −

City,State
Kochi,Kerala

Solution

To solve this, we will follow the steps given below.

  • Define a DataFrame

  • Check the city starts with ‘k’ as defined below,

df[df['City'].str.startswith('K') & df['State'].str.startswith('K')]
  • Finally, store the data in the ‘CSV’ file as below,

df1.to_csv(‘test.csv’)

Example

Let us see the following implementation to get a better understanding.

import pandas as pd
import random as r
data = { 'City': ['Chennai','Kochi','Kolkata'],'State':
['Tamilnad','Kerala','WestBengal']}
df = pd.DataFrame(data)
print("DataFrame is\n", df)
df1 = df[df['City'].str.startswith('K') & df['State'].str.startswith('K')]
df1.to_csv('test.csv')

Output

City,State
Kochi,Kerala

Updated on: 24-Feb-2021

537 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements