有人知道如何转置熊猫数据框吗,我有这样的数据集:
# 99564, Noam
Hop Company LLC, 10503 Cher rd
(123) 456-7890, Motor SR 5032
# 99843, Noam
Hop Prods, 902010 Rogg rd
(123) 456-7890, Ed CA 3534
# 99223, Noam
Skyline LLC, 12795 Rodf Road
(123) 456-7890, Sats Road 3922
我想将其转换为此:
# 99564, Noam, Hop Company LLC, 10503 Cher rd,(123) 456-7890, Motor SR 5032
# 99843, Noam, Hop Prods, 902010 Rogg rd, (123) 456-7890, Ed CA 3534
# 99223, Noam, Skyline LLC, 12795 Rodf Road, (123) 456-7890, Sats Road 3922
有人可以帮助我指导我如何做吗?
谢谢!
答案 0 :(得分:1)
如果结果已经存在于数据框中,则可以通过索引过滤对其进行整形,并通过两个concat将其重新加入。
df = pd.read_csv(StringIO(data),sep=',',header=None)
df2 = df.loc[~df.index.isin(df.iloc[::3].index.tolist())].reset_index(drop=True)
df2 = pd.concat([df2.iloc[::2].reset_index(drop=True),
df2.iloc[1::2].reset_index(drop=True)],axis=1,ignore_index=False)
final = pd.concat([df.iloc[::3].reset_index(drop=True),df2],axis=1)
print(final)
0 1 0 1 0 \
0 # 99564 Noam Hop Company LLC 10503 Cher rd (123) 456-7890
1 # 99843 Noam Hop Prods 902010 Rogg rd (123) 456-7890
2 # 99223 Noam Skyline LLC 12795 Rodf Road (123) 456-7890
1
0 Motor SR 5032
1 Ed CA 3534
2 Sats Road 3922