Pandas 如何将直方图转换为各种预定义的成分直方图?
比如说,我想做一顿含有多种成分的特定营养成分的饭:Pandas 如何将直方图转换为各种预定义的成分直方图?,pandas,dataframe,histogram,fft,Pandas,Dataframe,Histogram,Fft,比如说,我想做一顿含有多种成分的特定营养成分的饭: meal = a * ingredient_1 + b * ingredient_2 + c * ingredient_3 import pandas as pd df = pd.DataFrame( [ [ 'meal', 1625.14, 90.9, 47.214, 49.962, 138.16, 6.726, 6.60
meal = a * ingredient_1 + b * ingredient_2 + c * ingredient_3
import pandas as pd
df = pd.DataFrame(
[
[ 'meal', 1625.14, 90.9, 47.214, 49.962, 138.16, 6.726, 6.606, 28.858],
['ingredient_1', 109, 13.4, 4, 0.9, 4.4, 1.75, 0.3, 134],
['ingredient_2', 126, 0.8, 3.1, 19, 0.5, 0.4, 0.4, 0.4],
['ingredient_3', 35, 8, 0.1, 6.6, 1, 0.1, 0.1, 6.2],
],
columns = [
'name', 'calories', 'carbs', 'fat', 'fiber', 'protein', 'salt', 'saturated-fat', 'sugar'
]
)
有点像傅里叶变换如何将波形转换为正弦波的组合,一顿饭(营养成分的直方图)如何转换为成分的组合(其他营养成分的直方图)这样就可以提取出一组参数来描述每种配料的用量,以获得最适合的膳食
例如,在熊猫数据框中,我们有一餐和各种配料:
meal = a * ingredient_1 + b * ingredient_2 + c * ingredient_3
import pandas as pd
df = pd.DataFrame(
[
[ 'meal', 1625.14, 90.9, 47.214, 49.962, 138.16, 6.726, 6.606, 28.858],
['ingredient_1', 109, 13.4, 4, 0.9, 4.4, 1.75, 0.3, 134],
['ingredient_2', 126, 0.8, 3.1, 19, 0.5, 0.4, 0.4, 0.4],
['ingredient_3', 35, 8, 0.1, 6.6, 1, 0.1, 0.1, 6.2],
],
columns = [
'name', 'calories', 'carbs', 'fat', 'fiber', 'protein', 'salt', 'saturated-fat', 'sugar'
]
)
我猜你想要这样的东西:
#A
a1=df.loc[df.index.values.tolist()[1:],'calories'].tolist()
a2=df.loc[df.index.values.tolist()[1:],'carbs'].tolist()
a3=df.loc[df.index.values.tolist()[1:],'fat'].tolist()
A=np.array([a1,a2,a3])
#B
b1=df.loc[df.index.values.tolist()[0],'calories'].tolist()
b2=df.loc[df.index.values.tolist()[0],'carbs'].tolist()
b3=df.loc[df.index.values.tolist()[0],'fat'].tolist()
B=np.array([b1,b2,b3])
#Solve
X = np.linalg.solve(A,B)
df['Quantity']=[X.sum()]+X.tolist()
df_prop=df.loc[1:,['name','Quantity']].reset_index(drop=True).set_index('name')
#Libraries
import matplotlib.pyplot as plt
#for use Jupyter Notebook
%matplotlib inline
#Draw
ax=df_prop.plot(kind='bar',figsize=(15,15),fontsize=20)
ax.legend(fontsize=20)
输出:
X包含每种成分的量。如果您有任何问题,请随时提问