[英]Converting a data frame - Python
My data are in a data frame. 我的数据在数据框中。 It looks like this. 看起来像这样。
I am trying to convert the data frame into the following format: 我正在尝试将数据框转换为以下格式:
Currently I'm doing this conversion using the following Python codes, which are tedious. 目前,我正在使用以下乏味的Python代码进行此转换。
def f(row):
if row['d1'] == 1:
return 1
if row['d1'] == 2:
return ''
if row['d1'] == 3:
return ''
if row['d1'] == 4:
return ''
else:
return ''
return np.nan
df['t1']=df.apply(f, axis=1)
Any help would be greatly appreciated. 任何帮助将不胜感激。
You could apply following function: 您可以应用以下功能:
def func(x):
x.iloc[x.iloc[0]] = 1
return x
In [66]: df
Out[66]:
d1 t1 t2 t3 t4 t5
0 5 0 0 0 0 0
1 1 0 0 0 0 0
2 3 0 0 0 0 0
3 4 0 0 0 0 0
4 1 0 0 0 0 0
5 2 0 0 0 0 0
In [67]: df.apply(func, axis=1)
Out[67]:
d1 t1 t2 t3 t4 t5
0 5 0 0 0 0 1
1 1 1 0 0 0 0
2 3 0 0 1 0 0
3 4 0 0 0 1 0
4 1 1 0 0 0 0
5 2 0 1 0 0 0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.