
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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
- Related Articles
- Python - How to write pandas dataframe to a CSV file
- Write a program in Python to find the lowest value in a given DataFrame and store the lowest value in a new row and column
- Write a program in Python to export a given dataframe into Pickle file format and read the content from the Pickle file
- Write a Python code to filter palindrome names in a given dataframe
- Write a Python program to export dataframe into an Excel file with multiple sheets
- Write a program in Python to filter City column elements by removing the unique prefix in a given dataframe
- How to read a CSV file and store the values into an array in C#?
- Write a program in Python to print the ‘A’ grade students’ names from a DataFrame
- Write a Python code to read JSON data from a file and convert it to dataframe, CSV files
- Write a program in Python to transpose the index and columns in a given DataFrame
- MySQL query to find a list of city names that do not start with vowels?
- Writing a Pandas DataFrame to CSV file
- Write a Python program to export a dataframe to an html file
- Write a Python program to reshape a given dataframe in different ways
- Write a program in Python to convert a given dataframe to a LaTex document

Advertisements