【问题标题】:convert the type of specific elements in a column from DataFrame从 DataFrame 转换列中特定元素的类型
【发布时间】:2021-11-19 15:26:27
【问题描述】:

我有一个来自 DataFrame 的列,其中包含字符串格式的混合元素。我只想将字符串格式的数字转换为整数或通常转换为数值。应该保留“免费”这个词。

          price type
   0      '100' str
   1      free  str
   2      '80'  str
   3      '200' str
   4      free  str

输出应该如下所示

         price type
   0      100   int
   1      free  str
   2      80    int
   3      200   int
   4      free  str

所以我的问题是:

  • 有办法做到这一点吗?
  • pandas.Series 可能包含从字符串到整数的不同类型的元素?
  • 有一个函数可以在转换这个之前检查类型?像带有条件的 astype 之类的东西

【问题讨论】:

标签: python pandas string integer


【解决方案1】:

好吧,直接不可能有2种不同类型的系列,但让我试试下面的解决方案。

  1. 获取列的所有元素。
  2. 尝试转换为您的数据类型
  3. 放入[元素]
  4. 附加到列。

使用以下python代码

import pandas as pd
""" a.txt
price type
100 str
free str
80 str
200 str
free str
"""
df = pd.read_csv('a.txt', sep=" ")
new = []
for i in df.values:
    try:
        new.append([int(i[0])])
    except:
        new.append([str(i[0])])

df['new'] = new
print(df)

以下是输出的样子

  price type     new
0   100  str   [100]
1  free  str  [free]
2    80  str    [80]
3   200  str   [200]
4  free  str  [free]

现在,当您遍历值时,始终访问第 0 个位置,这将是您所需的数据类型

【讨论】:

  • 谢谢丹麦人!
猜你喜欢
  • 2021-09-25
  • 2018-05-15
  • 2015-02-06
  • 2016-04-28
  • 1970-01-01
  • 2012-12-13
  • 2011-10-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多