如何在 pandas 中的单个数据框列中乘以前两位数字?

How to multiply first two digit in a single dataframe column in pandas?

我已经尝试了很多方法来做到这一点,但它对我的情况不起作用。其中很多都是乘以列,因为我的情况是需要从单个列中获取前两位数字并相乘。

this is a column in a dataset and I need to get the first two-digit and multiply with each other 例如:对于第一行,我需要将 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(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)
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

如果您只想将第 1 位和第 2 位数字相乘

第一个数字和第二个数字相乘的函数,

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 或非数字值以避免错误。