我正在運行一個非常簡單的腳本(基本上是對具有更大資料集的腳本的測驗)
import pandas as pd
Data1 = {'First Name': ["Chris" , "John", "Jane"],
'Last Name': ["Potter","Doe", "Doe"],
'Age': ["23", "32", "31"]}
Data2 = {'First Name': ["George" , "John", "Jane"],
'Last Name': ["Hall","Doe", "Doe"],
'Age': ["27", "32", "31"]}
df1 = pd.DataFrame(Data1)
df2 = pd.DataFrame(Data2)
Comparison = df1.compare(df2, keep_shape=True, keep_equal=True)
print(df1)
print(df2)
print(Comparison)
這會生成一個如下所示的比較資料框:
First Name Last Name Age
self other self other self other
0 Chris George Potter Hall 23 27
1 John John Doe Doe 32 32
2 Jane Jane Doe Doe 31 31
我的問題是是否有辦法洗掉/操縱自我/其他行?我在谷歌上也找不到任何東西
uj5u.com熱心網友回復:
我認為你的字典可以是不可變的并且不能改變,除非以其他方式改變,例如下面的代碼,我能夠改變名字的零索引,然后將該字典列印到 Kronivar 正在改變
Data1 ['First Name'] [0] = 'Kronivar'
為了能夠使用drop()函式洗掉列,第一個引數是選擇列,然后我們設定值1來洗掉對應的列。
df1.drop(['First Name'],axis=1)
uj5u.com熱心網友回復:
如果要洗掉列索引的第二級,請使用droplevel:
>>> df1.compare(df2, keep_shape=True, keep_equal=True).droplevel(1, axis=1)
First Name First Name Last Name Last Name Age Age
0 Chris George Potter Hall 23 27
1 John John Doe Doe 32 32
2 Jane Jane Doe Doe 31 31
uj5u.com熱心網友回復:
- 您可以使用
reset_index:
由于reset_index僅適用于索引,您必須轉置,執行 reset_index 然后再次轉置:
Comparison = Comparison.T.reset_index(drop=True).T
這將重置您的列名稱。您必須在命令后再次設定名稱。
輸出:
0 1 2 3 4 5
0 Chris George Potter Hall 23 27
1 John John Doe Doe 32 32
2 Jane Jane Doe Doe 31 31
- 其他選項只是重命名
Comparison列:
只需在 之后再次設定您的列名稱df1.compare,如下所示:
Comparison.columns = [el[0] "_" el[1] for el in Comparison.columns.values]
輸出:
First Name_self First Name_other ... Age_self Age_other
0 Chris George ... 23 27
1 John John ... 32 32
2 Jane Jane ... 31 31
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/344016.html
上一篇:根據串列重命名列
下一篇:如何根據行在資料框中設定值?
