2024-09-24 02:15:42 发布
网友
如何在同一个数据帧内乘以的两列?我的数据帧如下图所示,我想这样输出。但,我无法找到如何将依赖于同一数据帧第一行的两列相乘。我真的很感激在这方面的帮助。在
request totalbytes /login 8520 /shuttle/countdown/ 7970 /shuttle/countdown/liftoff.html 0
到目前为止,我的输出如下,但我如何才能得到唯一的行。
既然你解释了你想要什么。。。您实际上想要删除重复项:
(df['bytesbytes']*df['bytesfrequency']).drop_duplicates()
它似乎只需要多个列:
df['totalbytes'] = df['bytesbytes']*df['bytesfrequency']
或使用^{}:
样品:
df = pd.DataFrame({'bytesbytes':[3985,1420,0,0], 'bytesfrequency':[2,6,2,2]}) df['totalbytes'] = df['bytesbytes']*df['bytesfrequency'] print (df) bytesbytes bytesfrequency totalbytes 0 3985 2 7970 1 1420 6 8520 2 0 2 0 3 0 2 0
但第一列request可能需要groupby,并使用^{}创建多个新的Series(两列都由transform转换,可能只需要一个):
request
groupby
Series
transform
df = pd.DataFrame({ 'request':['a','a','b','b'], 'bytesbytes':[3985,1420,1420,0], 'bytesfrequency':[2,6,6,2]}) g = df.groupby('request') print (g['bytesbytes'].transform('first')) 0 3985 1 3985 2 1420 3 1420 Name: bytesbytes, dtype: int64 print (g['bytesfrequency'].transform('first')) 0 2 1 2 2 6 3 6 Name: bytesfrequency, dtype: int64 df['totalbytes'] = g['bytesbytes'].transform('first')*g['bytesfrequency'].transform('first') print (df) bytesbytes bytesfrequency request totalbytes 0 3985 2 a 7970 1 1420 6 a 7970 2 1420 6 b 8520 3 0 2 b 8520
编辑:
如果需要按request列删除重复项:
df = pd.DataFrame({ 'request':['a','a','b','b'], 'bytesbytes':[3985,1420,1420,0], 'bytesfrequency':[2,6,6,2]}) print (df) bytesbytes bytesfrequency request 0 3985 2 a 1 1420 6 a 2 1420 6 b 3 0 2 b
单行解决方案-^{},多个和最后一个^{}列:
df = df.drop_duplicates('request') .assign(totalbytes=df['bytesbytes']*df['bytesfrequency']) .drop(['bytesbytes','bytesfrequency'], axis=1) print (df) request totalbytes 0 a 7970 2 b 8520
df = df.drop_duplicates('request') df['totalbytes'] = df['bytesbytes']*df['bytesfrequency'] df = df.drop(['bytesbytes','bytesfrequency'], axis=1) print (df) request totalbytes 0 a 7970 2 b 8520
获得你发布的预期结果的捷径
df.drop_duplicates().set_index('request').prod(1).reset_index(name='totalbytes') request totalbytes 0 /shuttle/countdown 7970 1 /login 8520 2 /shuttle/countdown/liftoff.html 0
既然你解释了你想要什么。。。您实际上想要删除重复项:
它似乎只需要多个列:
或使用^{} :
^{pr2}$样品:
但第一列} 创建多个新的
request
可能需要groupby
,并使用^{Series
(两列都由transform
转换,可能只需要一个):编辑:
如果需要按
request
列删除重复项:单行解决方案-^{} ,多个和最后一个^{} 列:
获得你发布的预期结果的捷径
相关问题 更多 >
编程相关推荐