[英]Convert Pandas df column list of strings to ints
我有一個這樣的 df”
col1
['525', '2830', '43', '567']
['432', '324', '3993', '5675']
['234', '2830', '342312', '4410']
df.applymap(type)
顯示此列中的所有行都是<class 'str'>
:
我正在嘗試將此 df.col 中的元素轉換為整數並將它們匯總到一個新列中。 我已經嘗試了十億次,但都沒有成功。
#attempts
#converted to list
map(int, list())
map(int, list().split())
#geeks for geeks suggestions:
for i in range(0, len(list)):
list[i] = int(list[i])
test_list = [int(i) for i in test_list]
我只是不斷收到此錯誤:
ValueError: invalid literal for int() with base 10: '[525 2830 3993 4410]'
有任何想法嗎?
df['sum'] = df['col1'].apply(lambda x: sum(int(v) for v in x))
print(df)
印刷:
col1 sum
0 [525, 2830, 43, 567] 3965
1 [432, 324, 3993, 5675] 10424
2 [234, 2830, 342312, 4410] 349786
編輯:
import ast
df['sum'] = df['col1'].apply(lambda x: sum(int(v) for v in ast.literal_eval(x)))
print(df)
嘗試這個
import ast
df.col1.map(lambda x: sum(map(int, ast.literal_eval(x))))
Out[789]:
0 3965
1 10424
2 349786
Name: col1, dtype: int64
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.