Pandas で DataFrame 列を文字列に変換する方法

Pandas DataFrame 列を文字列に変換するメソッドを紹介します。
- Pandas DataFrame シリーズの
astype(str)
メソッド - 列の要素を操作するための DataFrame
apply
メソッド
この記事では、以下の同じ DataFrame
を使用します。
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 シリーズの astype(str)
メソッド
Pandas シリーズ astype(dtype)
メソッドは、Pandas シリーズを指定された dtype
に変換しますタイプ。
pandas.Series.astype(str)
この記事のように Series、DataFrame 列を文字列に変換します。
>>> 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()
メソッドは DataFrame
データをインプレースで変更しないため、返された Pandas Series
を特定の DataFrame
列に割り当てる必要があります。
列の名前を角かっこで囲んでリストを作成することにより、複数の列を同時に文字列に変換することもできます。
>>> 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
メソッド
apply(func, *args, **kwds)
DataFrame
の apply
メソッドは関数 func
を各列または行に適用します。
簡単にするために、func
の代わりに lambda
関数を使用できます。
>>> 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
apply
メソッドを使用して関数を複数の列に適用することはできませんでした。
>>> 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
Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.
LinkedIn