Python Pandas : convert list of objects to a list of integer

标签 python pandas

嗨,我有一个问题将对象列表转换为整数列表。这些对象位于 Pandas 数据框“Kanten”的“stopsequence”列内。所有这些都是我在列中进行 CSV 导入和数据清理后收到的。我正在使用Python 3.X

我是一个Python新手,也许这就是问题的一部分。

import pandas as pd
import numpy as np
import os
import re
import ast
orgn_csv = pd.read_csv(r"Placeholder path for csv file")
df = orgn_csv.dropna()
Kanten = pd.DataFrame({"stopsequence" : df.stopsequence})

# In between is a block in which I use regular expressions for data cleaning purposes.
# I left the data cleaning block out to make the post shorter


Kanten.stopsequence = Kanten.stopsequence.str.split (',')
print (Kanten.head())
print (Kanten.stopsequence.dtype)                      

这给出了以下输出:

                                        stopsequence
2  [67, 945, 123, 122, 996, 995, 80, 81, 184, 990...
3  [67, 945, 123, 122, 996, 995, 80, 81, 184, 990...
4  [67, 945, 123, 122, 996, 995, 80, 81, 184, 990...
5  [67, 945, 123, 122, 996, 995, 80, 81, 184, 990...
6  [67, 945, 123, 122, 996, 995, 80, 81, 184, 990...
object

我正在寻找一种方法来转换包含对象的列表。我在 StackOverflow 论坛上进行了深入的搜索,并尝试了多种不同的方法。没有他们,我就成功了。 我尝试使用:

astype(str).astype(int)

Kanten.stopsequence = Kanten.stopsequence.astype(str).astype(int)
This Returns:
ValueError: invalid literal for int() with base 10:

改编了following post使用 atoi 代替 atof

Kanten.stopsequence.applymap(atoi)
This Returns:
AttributeError: 'Series' object has no attribute 'applymap'

list(map())

Kanten.stopsequence = list(map(int, Kanten.stopsequence))
This returns:
TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'

apply(ast.literal_eval)

Kanten.stopsequence = Kanten.stopsequence.apply(ast.literal_eval)
This returns:
TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'

有人能找到解决方案吗?我不确定这是一个复杂的情况还是我只是缺乏一些进一步的编程经验。如果可能的话,简短的解释会有所帮助。我自己可以再次找到解决方案。预先感谢您。

最佳答案

pandas Series 可以简单地转换为列表,并且可以将列表列表作为输入来创建 DataFrame

我认为这可能有帮助:

splitted = pd.DataFrame(Kanten.stopsequence.str.split (','), index=Kanten.index).astype(int)

这将为您提供一个新的数据框,其索引与原始数据框相同,但每个元素都位于其自己的列中。

如果相关,您可以连接新列

pd.concat([Kanten, splitted], axis=1)

关于Python Pandas : convert list of objects to a list of integer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55144642/

相关文章:

python - pandas:根据列值查找 df 中事件的首次发生并标记为新列值

python - 用装饰器替换宏样式的类方法?

python - PostGres 为数据帧返回 MemoryError

python - 如何使用时间点计算 Pandas 中的累积 groupby 计数?

python - 根据每个句子的第一个单词将 Pandas 数据框列中的字符串列表分解为新列

python - Pandas :取多个数据框的中位数

python - pandas 按切片分割数据框列

python - 使用具有多种数据类型的索引列表对 Pandas 系列对象进行切片

python - 在 Python Selenium 的 xpath 中使用变量

python - 如何从 Github 工作流程访问环境 secret ?