在读取CSV文件之后,我有一列包含一串用逗号分隔的十六进制值。例如“ 0x00000034,0x0000008a,0x00000145”。 我想将此列转换为整数列表。 我可以使用以下代码拆分并转换为整数列表:
for index, row in df.iterrows():
rnti_list = [int(idx, 16) for idx in row['rnti'].split(",")]
然后我可以将其添加为新列。
想知道最优雅的代码,可以用最少的行数完成相同的工作。
谢谢。
答案 0 :(得分:1)
使用嵌套列表理解:
df = pd.DataFrame({'rnti':['0x00000034,0x0000008a,0x00000145','0x00000034,0x0000008a']})
print (df)
rnti
0 0x00000034,0x0000008a,0x00000145
1 0x00000034,0x0000008a
rnti_list = [[int(idx, 16) for idx in x.split(",")] for x in df['rnti']]
print (rnti_list)
[[52, 138, 325], [52, 138]]
df['new'] = [[int(idx, 16) for idx in x.split(",")] for x in df['rnti']]
print (df)
rnti new
0 0x00000034,0x0000008a,0x00000145 [52, 138, 325]
1 0x00000034,0x0000008a [52, 138]
答案 1 :(得分:1)
使用apply
例如:
import pandas as pd
df = pd.DataFrame({"rnti": ["0x00000034,0x0000008a,0x00000145"]})
print( df["rnti"].str.split(",").apply(lambda x: [int(i, 16) for i in x]) )
输出:
0 [52, 138, 325]
Name: rnti, dtype: object