我有一个包含许多列的资料框,尤其是包含一个阵列值的列,例如:
Name City Details
Nicolas Paris [1 5 3 2]
Adam Rome [5 3 45 0]
我尝试将详细信息列与标量相乘
df_results.loc[:,'Values'] = df_results.loc[:,'Values'].mul(5)
# or like that
df_results.loc[:,'Values'] = df_results['Values'] * 5
但我收到此讯息不能将序列乘以“float”型别的非整数
预期成绩
Name City Details
Nicolas Paris [5 25 15 10]
Adam Rome [25 15 225 0]
有任何想法吗?
uj5u.com热心网友回复:
applymap
与检查单元格型别的条件一起使用:
x = [
["Name","City","Details"],
["Nicolas","Paris",[1,5,3,2]],
["Adam","Rome",[5,3,45,0]],
]
import pandas as pd
df = pd.DataFrame(x)
df.applymap(lambda x: [y*2 for y in x] if isinstance(x, list) else x)
如果它是一个串列,使用串列理解来应用一些操作(如乘以 2)
uj5u.com热心网友回复:
也可以通过使用 numpy 来做到这一点:
import pandas as pd
import numpy as np
df=pd.DataFrame(columns=['Name','City','Details'])
df['Name']=['Nicolas','Adam']
df['City']=['Paris','NY']
df['Details']=[[1,5,3,2],[5,3,45,0]]
df['Details']=[np.array(i)*5 for i in df['Details'].values]
结果:
Name City Details
0 Nicolas Paris [5, 25, 15, 10]
1 Adam NY [25, 15, 225, 0]
uj5u.com热心网友回复:
如果您只想乘以“详细信息”列,则可以 通过使用 apply 而不是 applymap 并且不检查它是否是串列来简化DSteman 的答案:
import pandas as pd
df_results = pd.DataFrame({
'Name': ['Nicolas', 'Adam'],
'City': ['Paris', 'Rome'],
'Details': [[1, 5, 3, 2], [5, 3, 45, 0]]
})
df_results['Details'] = df_results['Details'].apply(lambda x: [value * 5 for value in x])
导致:
Name City Details
0 Nicolas Paris [5, 25, 15, 10]
1 Adam Rome [25, 15, 225, 0]
uj5u.com热心网友回复:
df['Details'] = df['Details'].map(lambda x: [value * 5 for value in x])
0 评论