Python 以所需格式打印数据帧
我有以下表格中的数据:Python 以所需格式打印数据帧,python,pandas,dataframe,Python,Pandas,Dataframe,我有以下表格中的数据: Sample Cohort CName Intensity S1 a C1 22.34 S2 a C2 17.34 我想用这张表格打印出来 Cohort Intensity1 Intensity2 a 22.34 17.34 请建议怎么做。我是熊猫的初学者我想你需要: 或: 最后: df.columns = ['Intensity' + str(x + 1) for x in np
Sample Cohort CName Intensity
S1 a C1 22.34
S2 a C2 17.34
我想用这张表格打印出来
Cohort Intensity1 Intensity2
a 22.34 17.34
请建议怎么做。我是熊猫的初学者我想你需要:
或:
最后:
df.columns = ['Intensity' + str(x + 1) for x in np.arange(len(df.columns))]
print (df)
Intensity1 Intensity2
Cohort
a 22.34 17.34
但可能需要:
print (df)
Sample Cohort CName Intensity
0 S1 a C1 22.34
1 S2 a C2 17.34
2 S1 b C1 20.00
3 S1 b C1 10.00
df['g'] = df.groupby('Cohort').cumcount()
df = df.pivot(index='Cohort', columns='g', values='Intensity')
print (df)
g 0 1
Cohort
a 22.34 17.34
b 20.00 10.00
这与:
df = pd.pivot(index=df['Cohort'],
columns=df.groupby('Cohort').cumcount(),
values=df['Intensity'])
print (df)
0 1
Cohort
a 22.34 17.34
b 20.00 10.00
备选方案:
df['g'] = df.groupby('Cohort').cumcount()
df = df.set_index(['Cohort', 'g'])['Intensity'].unstack(fill_value=0)
print (df)
g 0 1
Cohort
a 22.34 17.34
b 20.00 10.00
你能多加几行吗?5-6号很好。谢谢
df = pd.pivot(index=df['Cohort'],
columns=df.groupby('Cohort').cumcount(),
values=df['Intensity'])
print (df)
0 1
Cohort
a 22.34 17.34
b 20.00 10.00
df['g'] = df.groupby('Cohort').cumcount()
df = df.set_index(['Cohort', 'g'])['Intensity'].unstack(fill_value=0)
print (df)
g 0 1
Cohort
a 22.34 17.34
b 20.00 10.00