[英]Pandas fill column with row value
I have a dataframe that look like this.我有一个 dataframe,看起来像这样。
key values
Interface InterfaceA
State Up
Line Status Up
ID 9000
Interface InterfaceB
State Down
Line Status Down
ID 9001
And I would like to transform it to become like this我想把它变成这样
Interface State Line Status ID
InterfaceA Up Up 9000
InterfaceB Down Down 9001
I've try to use loc to insert the column by column, but when it reaches 2nd columns我尝试使用 loc 逐列插入,但是当它到达第二列时
ValueError: cannot reindex from a duplicate axis ValueError:无法从重复轴重新索引
the above error appears.出现上述错误。
final_df['Interface'] = commands_df.loc[commands_df['key'].str.contains('Interface'), 'values']
final_df['State'] = commands_df.loc[commands_df['key'].str.contains('State'), 'values'] <-- Error starts here
ValueError: cannot reindex from a duplicate axis
df = df.assign(Interface=df[df['key'] == 'Interface']['values']).ffill()
print(df.pivot(index='Interface', columns='key', values='values').drop(columns='Interface'))
Prints:印刷:
key ID Line Status State
Interface
InterfaceA 9000 Up Up
InterfaceB 9001 Down Down
Here is a possible solution-这是一个可能的解决方案-
import pandas as pd
df = pd.DataFrame(data=['InterfaceA', 'Up', 'Up', 9000, 'InterfaceB', 'Down', 'Down', 9001],
index=['Interface', 'State', 'Line Status', 'ID', 'Interface', 'State', 'Line Status', 'ID'])
df = df.T
print(df.groupby(df.columns.values, axis=1).agg(lambda x: x.values.tolist()).sum().apply(pd.Series).T)
ID Interface Line Status State
0 9000 InterfaceA Up Up
1 9001 InterfaceB Down Down
A simple set_index
with cumcount
and unstack
带有cumcount
和unstack
的简单set_index
df_final = df.set_index([df.groupby('key').cumcount(),'key'])['values'].unstack()
Out[423]:
key ID Interface Line-Status State
0 9000 InterfaceA Up Up
1 9001 InterfaceB Down Down
Another method is using pd.crosstab
另一种方法是使用pd.crosstab
df_final = pd.crosstab(df.groupby('key')['values'].cumcount(),
df['key'],
df['values'], aggfunc='first')
Out[424]:
key ID Interface Line-Status State
row_0
0 9000 InterfaceA Up Up
1 9001 InterfaceB Down Down
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.