while I want to get the DataFrame structure is like: b" referrerpolicy="no-referrer" style="max-width:100%"> where the b is like the transpose of a. By convert a to b, I use th"/>
I have a pandas.Dataframe
called a
and the structure is as follows:
while I want to get the DataFrame
structure is like:
where the b
is like the transpose of a
. By convert a
to b
, I use the code :
id_uni = a['id'].unique()
b = pd.DataFrame(columns=['id']+[str(i) for i in range(1,4)])
b['id'] = id_uni
for i in id_uni:
for j in range(7):
ind = (a['id'] == i) & (a['w'] == j)
med = a.loc[ind, 't'].values
if med:
b.loc[b['id'] == i, str(j)] = med[0]
else:
b.loc[b['id'] == i, str(j)] = 0
The method is very brutal that I just use two for-loops to get all elements from a
to b
. And it is very slow. Do you have an efficient way to improve it?
You can use pivot
:
print (df.pivot(index='id', columns='w', values='t'))
w 1 2 3
id
0 54 147 12
1 1 0 1
df1 = df.pivot(index='id', columns='w', values='t').reset_index()
df1.columns.name=None
print (df1)
id 1 2 3
0 0 54 147 12
1 1 1 0 1
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.