Pandas: Convert Multiple Columns To String
I have some columns ['a', 'b', 'c', etc.] (a and c are float64 while b is object) I would like to convert all columns to string and preserve nans. Tried using df[['a', 'b', 'c']] =
Solution 1:
This gives you the list of column names
lst = list(df)
This converts all the columns to string type
df[lst] = df[lst].astype(str)
Solution 2:
df = pd.DataFrame({
'a': [23.0, 51.0, np.nan, 24.0],
'b': ["a42", "3", np.nan, "a1"],
'c': [142.0, 12.0, np.nan, np.nan]})
for col in df:
df[col] = [np.nan if (notisinstance(val, str) and np.isnan(val)) else
(val ifisinstance(val, str) elsestr(int(val)))
for val in df[col].tolist()]
>>> df
a b c
023 a42 1421513122 NaN NaN NaN
324 a1 NaN
>>> df.values
array([['23', 'a42', '142'],
['51', '3', '12'],
[nan, nan, nan],
['24', 'a1', nan]], dtype=object)
Solution 3:
You could apply .astype()
function on every elements of dataframe, or could select the column of interest to convert to string by following ways too.
In [41]: df1 = pd.DataFrame({
...: 'a': [23.0, 51.0, np.nan, 24.0],
...: 'b': ["a42", "3", np.nan, "a1"],
...: 'c': [142.0, 12.0, np.nan, np.nan]})
...:
In [42]:
In [42]: df1
Out[42]:
a b c
023.0 a42 142.0151.0312.02 NaN NaN NaN
324.0 a1 NaN
### Shows current data type of the columns:
In [43]: df1.dtypes
Out[43]:
a float64
b object
c float64
dtype: object### Applying .astype() on each element of the dataframe converts the datatype to string
In [45]: df1.astype(str).dtypes
Out[45]:
a object
b object
c object
dtype: object### Or, you could select the column of interest to convert it to strings
In [48]: df1[["a", "b", "c"]] = df1[["a","b", "c"]].astype(str)
In [49]: df1.dtypes ### Datatype update
Out[49]:
a object
b object
c object
dtype: object
Solution 4:
I did this way.
get all your value from a specific column, e.g. 'text'.
k = df['text'].values
then, run each value into a new declared string, e.g. 'thestring'
thestring = ""for i in range(0,len(k)):
thestring += k[i]
print(thestring)
hence, all string in column pandas 'text' has been put into one string variable.
cheers, fairuz
Post a Comment for "Pandas: Convert Multiple Columns To String"