![](/img/trans.png)
[英]Pandas: How to expand data frame rows containing a dictionary with varying keys in a column?
[英]How to add new rows to a Pandas Data Frame with varying column numbers?
我想在 Pandas 數據幀中添加新行,而不考慮每個新行中的順序和列數。
當我添加新行時,我希望我的數據框如下所示。 每行可以有不同數量的列。
---- | 1 | 2 | 3 | 4
row1 | data | data |
row2 | data | data | data
row3 | data |
row4 | data | data | data | data
一次一行地構建 pandas DataFrames 通常非常慢。 一種解決方案是首先將數據收集到字典中,然后將其轉換為 dataframe 進行進一步處理:
d = {
'att1': ['a', 'b'],
'att2': ['c', 'd', 'e'],
'att3': ['f'],
'att4': ['g', 'h', 'i', 'j'],
}
df = pd.DataFrame.from_dict(d, orient='index')
這導致df
包含:
0 1 2 3
att1 a b None None
att2 c d e None
att3 f None None None
att4 g h i j
或者更符合典型的 pandas 格式,將數據存儲在一個長系列中,其中“att1”用作值“a”和“b”等的索引:
series = df.stack().reset_index(level=1, drop=True)
它允許輕松選擇各種屬性:
series.loc[['att1', 'att3']]
返回:
att1 a
att1 b
att3 f
在 pandas 中,您可以將新行與現有數據框連接起來(即使新行具有不同的列數),如下所示。
import pandas as pd
df = pd.DataFrame([list(range(5))])
new_row = pd.DataFrame([list(range(4))])
pd.concat([df,new_row], ignore_index=True, axis=0)
在上面的代碼片段中,pd.concatenate function 合並了兩個數據幀。 如果您提供參數 ignore_index=True,pandas 將合並兩個數據幀而不考慮它們的長度。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.