Python 如何将pandas中单个数据帧列的前两位数相乘?
我尝试了很多方法,但对我的情况不起作用。它们中的许多是用列相乘的,因为我的情况是需要从单个列中获得前两位数字并相乘 例如:对于第一行,我需要得到4乘以5,结果将存储在一个新列中 我可以知道怎么做吗 感谢您在高级^ ^中这样说:Python 如何将pandas中单个数据帧列的前两位数相乘?,python,pandas,dataframe,jupyter-notebook,multiplication,Python,Pandas,Dataframe,Jupyter Notebook,Multiplication,我尝试了很多方法,但对我的情况不起作用。它们中的许多是用列相乘的,因为我的情况是需要从单个列中获得前两位数字并相乘 例如:对于第一行,我需要得到4乘以5,结果将存储在一个新列中 我可以知道怎么做吗 感谢您在高级^ ^中这样说: ID = ['45.0', '141.0', '191.0', '143.0', '243.0'] N = [f"{int(s[0])*int(s[1])}" for s in ID] print(
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']
这应该行得通
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
用于以下数据帧
import pandas as pd
d={'locationID':[12,234,34]}
data=pd.DataFrame(data=d)
如果你想把所有数字相乘
函数将所有数字相乘
def multiplyall(number):
result=1
for i in range(len(str(number))):
result=int(str(number)[i])*result
return result
使用insert(位置、列名、列值)
您将获得以下输出
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
或非数值,以避免错误。欢迎使用StackOverflow。好的答案需要好的问题。请查看以及如何提供。您可以编辑您的问题以便于获得帮助。请从中重复。非常感谢您的详细解释!很高兴提供帮助,如果此答案解决了您的问题,请单击答案旁边的复选标记将其标记为已接受。请参阅:更多信息,非常感谢,这确实对我的情况有效。=)
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