我有一个类似于的数据帧
principalDf =
| x || y || z || values |
| x0 || y0 || z0 || areal |
| x1 || y1 || z1 || aimag |
| x2 || y2 || z2 || breal |
| x3 || y3 || z3 || bimag |
我想生产:
frobprincipalDf =
| x || y || z || values |
|sqrt(x0^2+x1^2)||sqrt(y0^2+y1^2)||sqrt(z0^2+z1^2)|| a |
|sqrt(x2^2+x3^2)||sqrt(y2^2+y3^2)||sqrt(z2^2+z3^2)|| b |
我通过以下方式生成所需的x、y和z数据:
frobprincipalDf = pd.DataFrame(columns=principalDf.columns)
for col in principalDf.columns[:-1]:
for index in range(0,len(principalDf),2):
frobnorm = np.sqrt(principalDf[col].iloc[index]**2+principalDf[col].iloc[index+1]**2)
print(frobnorm)
如何将frobnorm添加到新创建的frobprincipalDf
中的特定col
?
有比嵌套for循环更好的方法吗?
它应该适用于任何值名称,这样,如果另一个值以a开头,它就不会将它们"分组"在一起。
下面似乎是偶数行索引对添加的初始问题的完整解决方案。这是对类人类答案的略微修改。不过,向特定的df
列添加单个值的次要问题仍然存在。
frobprincipalDf = np.sqrt(principalDf[['x', 'y', 'z']].shift() ** 2 + principalDf[['x', 'y', 'z']] ** 2)
frobprincipalDf = pd.concat([frobprincipalDf,principalDf['values'].str[:2]], axis=1)
frobprincipalDf = frobprincipalDf[frobprincipalDf.index % 2 == 1].reset_index(drop=True)
您可以使用groupby
+agg
:
import numpy as np
group = df['values'].str.extract('(.*)(?:real|imag)', expand=False)
# 0 a
# 1 a
# 2 b
# 3 b
(df.select_dtypes('number')
.groupby(group)
.agg(lambda x: np.sqrt((x**2).sum()))
.reset_index()
)
示例输入:
x y z values
0 1 2 3 areal
1 4 5 6 aimag
2 7 8 9 breal
3 10 11 12 bimag
输出:
values x y z
0 a 4.123106 5.385165 6.708204
1 b 12.206556 13.601471 15.000000
您可以使用shift
方法来挑选一对行。
代码:
import numpy as np
import pandas as pd
# Create a sample dataframe
import io
s='''x,y,z,values
1,5,9,areal
2,6,10,aimag
3,7,11,breal
4,8,12,bimag'''
df = pd.read_csv(io.StringIO(s))
# Calculate values
df_calc = np.sqrt(df[['x', 'y', 'z']].shift() ** 2 + df[['x', 'y', 'z']] ** 2)
# Deal with strings
df_str = df['values'].str[:1]
# Concatenate the two dataframes
df_result = pd.concat([df_calc, df_str], axis=1)
# Pick out odd indice
df_result = df_result[df_result.index % 2 == 1].reset_index(drop=True)
输入:
x | y | z | >值 |
---|---|---|---|
1 | |||
2 | 6 | 0>td style="text-align:center;">aimag//tr>||
3 | 7 | 11 | >breal|
4 | 8 | 12 | bimag |