我有一个非常大的数据框,我想避免遍历每一行,并希望将整个列从十六进制字符串转换为 int。它不能使用 astype 正确处理字符串,但单个条目没有问题。有没有办法告诉 astype 数据类型是 base 16?
IN:
import pandas as pd
df = pd.DataFrame(['1C8','0C3'], columns=['Command0'])
df['Command0'].astype(int)
OUT:
ValueError: invalid literal for int() with base10: '1C8'
这可行,但要避免行迭代。
for index, row in df.iterrows():
print(row['Command0'])
我正在从 CSV pd.read_csv(open_csv, nrows=20)
中读取它,所以如果有一种方法可以读取它并明确告诉它格式是什么,那将变得更好!
最佳答案
您可以按照 @Andrew's solution 使用 apply
,但是 lambda
不是必需的并且会增加开销。相反,使用带有关键字参数的 apply
:
res = df['Command0'].apply(int, base=16)
print(res)
0 456
1 195
Name: Command0, dtype: int64
通过pd.read_csv
,您可以使用functools.partial
:
from functools import partial
df = pd.read_csv(open_csv, nrows=20, converters={'Command0': partial(int, base=16)})
关于python - 将 pandas dataframe 列从十六进制字符串转换为 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37955856/