JIYIK CN >

Current Location:Home > Learning > PROGRAM > Python >

How to Convert DataFrame Column to String in Pandas

Author:JIYIK Last Updated:2025/05/02 Views:

We will look at methods for converting Pandas DataFrame columns to strings.

  • Pandas Series.astype(str)Method
  • DataFrame.apply()Methods operate on the elements in a column

We will use the same DataFrame below in this article.

import pandas as pd

df = pd.DataFrame({"A": [1, 2, 3], "B": [4.1, 5.2, 6.3], "C": ["7", "8", "9"]})

print(df)
print(df.dtypes)
   A    B  C
0  1  4.1  7
1  2  5.2  8
2  3  6.3  9

A      int64
B    float64
C     object
dtype: object

Pandas DataFrame Series.astype(str)feature

Pandas Series.astype(dtype) method converts a Pandas Series to the specified dtypedtype.

pandas.Series.astype(str)

As mentioned in this article, it converts Series, DataFrame columns to strings.

>>> df
   A    B  C
0  1  4.1  7
1  2  5.2  8
2  3  6.3  9
>>> df['A'] = df['A'].astype(str)
>>> df
   A    B  C
0  1  4.1  7
1  2  5.2  8
2  3  6.3  9
>>> df.dtypes
A     object
B    float64
C     object
dtype: object

astype()method does not modify the DataFrame data in-place, so we need to assign the returned Pandas Series to a specific DataFrame column.

We can also convert multiple columns to strings at once by enclosing the names within square brackets to form a list.

>>> df[['A','B']] = df[['A','B']].astype(str)
>>> df
   A    B  C
0  1  4.1  7
1  2  5.2  8
2  3  6.3  9
>>> df.dtypes
A    object
B    object
C    object
dtype: object

DataFrame.apply()Methods operate on the elements in a column

apply(func, *args, **kwds)

DataFrame.apply()method funcapplies a function to each column or row.

For simplicity, we can use lambdathe function instead func.

>>> df['A'] = df['A'].apply(lambda _: str(_))
>>> df
   A    B  C
0  1  4.1  7
1  2  5.2  8
2  3  6.3  9
>>> df.dtypes
A     object
B    float64
C     object
dtype: object

You cannot applyapply a function to multiple columns using the method.

>>> df[['A','B']] = df[['A','B']].apply(lambda _: str(_))
Traceback (most recent call last):
  File "<pyshell#31>", line 1, in <module>
    df[['A','B']] = df[['A','B']].apply(lambda _: str(_))
  File "D:\WinPython\WPy-3661\python-3.6.6.amd64\lib\site-packages\pandas\core\frame.py", line 3116, in __setitem__
    self._setitem_array(key, value)
  File "D:\WinPython\WPy-3661\python-3.6.6.amd64\lib\site-packages\pandas\core\frame.py", line 3144, in _setitem_array
    self.loc._setitem_with_indexer((slice(None), indexer), value)
  File "D:\WinPython\WPy-3661\python-3.6.6.amd64\lib\site-packages\pandas\core\indexing.py", line 606, in _setitem_with_indexer
    raise ValueError('Must have equal len keys and value '
ValueError: Must have equal len keys and value when setting with an iterable

For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.

Article URL:

Related Articles

Convert Pandas to CSV without index

Publish Date:2025/05/01 Views:159 Category:Python

As you know, an index can be thought of as a reference point used to store and access records in a DataFrame. They are unique for each row and usually range from 0 to the last row of the DataFrame, but we can also have serial numbers, dates

Convert Pandas DataFrame to Dictionary

Publish Date:2025/05/01 Views:198 Category:Python

This tutorial will show you how to convert a Pandas DataFrame into a dictionary with the index column elements as keys and the corresponding elements of other columns as values. We will use the following DataFrame in the article. import pan

Convert Pandas DataFrame columns to lists

Publish Date:2025/05/01 Views:192 Category:Python

When working with Pandas DataFrames in Python, you often need to convert the columns of the DataFrame into Python lists. This process is very important for various data manipulation and analysis tasks. Fortunately, Pandas provides several m

Subtracting Two Columns in Pandas DataFrame

Publish Date:2025/05/01 Views:120 Category:Python

Pandas can handle very large data sets and has a variety of functions and operations that can be applied to the data. One of the simple operations is to subtract two columns and store the result in a new column, which we will discuss in thi

Dropping columns by index in Pandas DataFrame

Publish Date:2025/05/01 Views:99 Category:Python

DataFrames can be very large and can contain hundreds of rows and columns. It is necessary to master the basic maintenance operations of DataFrames, such as deleting multiple columns. We can use dataframe.drop() the method to delete columns

Pandas Copy DataFrame

Publish Date:2025/05/01 Views:53 Category:Python

This tutorial will show you how to DataFrame.copy() copy a DataFrame object using the copy method. import pandas as pd items_df = pd . DataFrame( { "Id" : [ 302 , 504 , 708 ], "Cost" : [ "300" , "400" , "350" ], } ) print (items_df) Output:

Pandas DataFrame.ix[] Function

Publish Date:2025/05/01 Views:169 Category:Python

Python Pandas DataFrame.ix[] function slices rows or columns based on the value of the argument. pandas.DataFrame.ix[] grammar DataFrame . ix[index = None , label = None ] parameter index Integer or list of integers used to slice row indice

Pandas DataFrame.describe() Function

Publish Date:2025/05/01 Views:120 Category:Python

Python Pandas DataFrame.describe() function returns the statistics of a DataFrame. pandas.DataFrame.describe() grammar DataFrame . describe( percentiles = None , include = None , exclude = None , datetime_is_numeric = False ) parameter perc

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial