大 pandas :将多列转换为字符串

编程入门 行业动态 更新时间:2024-10-19 19:34:09
本文介绍了大 pandas :将多列转换为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一些列['a', 'b', 'c', etc.](a和c是float64,而b是object)

I have some columns ['a', 'b', 'c', etc.] (a and c are float64 while b is object)

我想将所有列都转换为字符串并保留nan s.

I would like to convert all columns to string and preserve nans.

使用df[['a', 'b', 'c']] == df[['a', 'b', 'c']].astype(str)进行了尝试,但float64列留空.

Tried using df[['a', 'b', 'c']] == df[['a', 'b', 'c']].astype(str) but that left blanks for the float64 columns.

目前,我正在与以下各项进行逐一比较:

Currently I am going through one by one with the following:

df['a'] = df['a'].apply(str) df['a'] = df['a'].replace('nan', np.nan)

使用.astype(str)然后用np.nan替换''的最佳方法是吗? 侧面问题:.astype(str)和.apply(str)之间有区别吗?

Is the best way to use .astype(str) and then replace '' with np.nan? Side question: is there a difference between .astype(str) and .apply(str)?

样本输入:(dtypes:a = float64,b = object,c = float64)

Sample Input: (dtypes: a=float64, b=object, c=float64)

a, b, c, etc. 23, 'a42', 142, etc. 51, '3', 12, etc. NaN, NaN, NaN, etc. 24, 'a1', NaN, etc.

所需的输出:(dtypes:a =对象,b =对象,c =对象)

Desired output: (dtypes: a=object, b=object, c=object)

a, b, c, etc. '23', 'a42', '142', etc. '51', 'a3', '12', etc. NaN, NaN, NaN, etc. '24', 'a1', NaN, etc.

推荐答案

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 (not isinstance(val, str) and np.isnan(val)) else (val if isinstance(val, str) else str(int(val))) for val in df[col].tolist()] >>> df a b c 0 23 a42 142 1 51 3 12 2 NaN NaN NaN 3 24 a1 NaN >>> df.values array([['23', 'a42', '142'], ['51', '3', '12'], [nan, nan, nan], ['24', 'a1', nan]], dtype=object)

更多推荐

大 pandas :将多列转换为字符串

本文发布于:2023-10-27 11:10:52,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1533198.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:转换为   字符串   pandas   将多列

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!