我已经尝试了许多方法来执行此操作,但不适用于我的情况。其中许多都与列相乘,对于我来说,需要从单个列中获取前两位并相乘。
this is a column in a dataset and I need to get the first two-digit and multiply with each other 例如:对于第一行,我需要将4乘以5,结果将存储在新列中
我可以知道怎么做吗?
谢谢你^^
答案 0 :(得分:0)
赞:
ID = ['45.0',
'141.0',
'191.0',
'143.0',
'243.0']
N = [f"{int(s[0])*int(s[1])}" for s in ID]
print(N)
输出:
['20',
'4',
'9',
'4',
'8']
答案 1 :(得分:0)
这应该有效
data = DataFrame([
(54423),
(2023),
(4353),
(76754)
], columns=["number_1"])
data["number_2"] = 0
def calculation(num):
mult = num
if len(str(num)) >= 2:
str_num = str(num)
mult = int(str_num[0]) * int(str_num[1])
return mult
data["number_2"] = data["number_1"].apply(calculation)
print(data)
number_1 number_2
0 54423 20
1 2023 0
2 4353 12
3 76754 42
答案 2 :(得分:0)
用于后续数据框
import pandas as pd
d={'locationID':[12,234,34]}
data=pd.DataFrame(data=d)
print(data)
locationID
0 12
1 234
2 34
用于将所有数字相乘的功能
def multiplyall(number):
result=1
for i in range(len(str(number))):
result=int(str(number)[i])*result
return result
使用insert(location, column name, column values)
在一行中根据功能创建列并添加值
data.insert(len(data.columns), 'new_column', data['locationID'].apply(lambda x: multiply_all(x)).tolist())
您将获得以下输出
print(data)
locationID new_column
0 12 2
1 234 24
2 34 12
用于将第一位和第二位数字相乘的功能
def multiply_firstsecond(number):
result=number
if len(str(number))>1:
result=int(str(number)[0])* int(str(number)[1])
return result
类似地,
data.insert(len(data.columns), 'new_column', data['locationID'].apply(lambda x: multiply_firstsecond(x)).tolist())
此输出,
print(data)
locationID new_column
0 12 2
1 234 6
2 34 12
请确保您在该列中没有NaN
或非数字值,以免发生错误。