[英]How can I create a new column on a Pandas Dataframe with conditions based on previous and next row?
[英]how can I create new table based on the previous table in pandas?
本文的后續操作如何根據Pandas數據框中的列表對索引行進行重新排序
import pandas as pd
df = pd.DataFrame({'name' : ['A', 'Z','C'],
'company' : ['Apple', 'Yahoo','Amazon'],
'height' : [130, 150,173]})
df = df.pivot(index="name", columns="company", values="height").fillna(0)
df.reindex(["Z", "C", "A"])
company Amazon Apple Yahoo
name
Z 0.0 0.0 150.0
C. 173.0 0.0 0.0
A 0.0 130.0 0.0
我想知道是否添加了更多數據,並通過遵循此鏈接來執行此操作? 是否可以僅復制Pandas DataFrame的結構(而不是數據)?
df_1 = pd.DataFrame({'name' : ['A','Z','B','C','D'],
'company' : ['Apple','Yahoo','Alebaba','Amazon','Google'],
'height' : [130, 150,160,173,180]})
df_1 = df_1.pivot(index="name", columns="company", values="height").fillna(0)
df_1 = df_1.reindex_like(df)
結果如下
company Amazon Apple Yahoo
name
Z 0.0 0.0 150.0
C 173.0 0.0 0.0
A 0.0 130.0 0.0
但我希望看到這樣的結果
company Amazon Apple Yahoo Alebaba Google
name
Z 0.0 0.0 150.0 0.0 0.0
C 173.0 0.0 0.0 0.0 0.0
A 0.0 130.0 0.0 0.0 0.0
B 0.0 0.0 0.0 160.0 0.0
D 0.0 0.0 0.0 0.0 180.0
較小的數據就可以了,但是如果有數千個數據,我該如何解決此問題?
要添加到先前數據中的數據集可以位於任何位置。
有什么建議嗎? TT
將Index.difference
與Index.append
用於沒有排序值的新Index和column值,並通過DataFrame.reindex
更改位置:
print (df_1.index.difference(df.index))
Index(['B', 'D'], dtype='object', name='name')
print (df.index.append(df_1.index.difference(df.index)))
Index(['Z', 'C', 'A', 'B', 'D'], dtype='object', name='name')
idx = df.index.append(df_1.index.difference(df.index))
cols = df.columns.append(df_1.columns.difference(df.columns))
df_1 = df_1.reindex(index=idx, columns=cols)
print (df_1)
company Amazon Apple Yahoo Alebaba Google
name
Z 0.0 0.0 150.0 0.0 0.0
C 173.0 0.0 0.0 0.0 0.0
A 0.0 130.0 0.0 0.0 0.0
B 0.0 0.0 0.0 160.0 0.0
D 0.0 0.0 0.0 0.0 180.0
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.