简体   繁体   English

Pandas 用行值填充列

[英]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

credits to this answer归功于这个答案

A simple set_index with cumcount and unstack带有cumcountunstack的简单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.

相关问题 用 Pandas 中的前一行列填充当前行和列值 - Fill current row and column value with previous row column in Pandas Pandas:同列不同行如何填写值 - Pandas:How to fill in value from the same column but different row 根据Pandas中第二列的条件,用另一行的同一列的值填充特定行的列中的值 - Fill values in a column of a particular row with the value of same column from another row based on a condition on second column in Pandas Pandas Dataframe逐行填充新列 - Pandas Dataframe row by row fill new column 如何使用pandas数据帧中第一行和相应行之间的列的平均值填充特定值 - How to fill a particular value with mean value of the column between first row and the corresponding row in pandas dataframe 使用pandas在csv文件的同一行上填充下一列值的行中的空值 - Fill empty values from a row with the value of next column on the same row on csv file with pandas 使用熊猫使用另一列中的值填充特定列中的空白行 - Fill Blank Row in a specific column with value from another column using pandas 在熊猫的特定行和列中填充NaN - Fill NaN in specific row and column in Pandas 用行号填充新的 pandas 列 - Fill a new pandas column with row numbers Python/Pandas:如果值为 NaN 或 0,则用同一行内下一列的值填充 - Python/Pandas: if value is NaN or 0 then fill with the value from the next column within the same row
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM