[英]add columns different length pandas
我在pandas中添加列有問題。我有DataFrame,維度是nxk。 在這個過程中,我需要添加維度為 mx1 的列,其中 m = [1,n],但我不知道 m。
當我嘗試這樣做時:
df['Name column'] = data
# type(data) = list
結果:
AssertionError: Length of values does not match length of index
我可以添加不同長度的列嗎?
如果您使用已接受的答案,您將丟失列名,如已接受的答案示例中所示,並在文檔中進行了描述(強調已添加):
產生的軸將被標記為0,...,N - 1。這如果你是哪里串聯串列軸線沒有意義的索引信息的對象是非常有用的。
看起來列名( 'Name column'
)對原始海報/原始問題有意義。
為了節省列名,使用pandas.concat
,但不要ignore_index
(默認值ignore_index
是false
,所以您完全可以忽略這樣的說法)。 繼續使用axis=1
:
import pandas
# Note these columns have 3 rows of values:
original = pandas.DataFrame({
'Age':[10, 12, 13],
'Gender':['M','F','F']
})
# Note this column has 4 rows of values:
additional = pandas.DataFrame({
'Name': ['Nate A', 'Jessie A', 'Daniel H', 'John D']
})
new = pandas.concat([original, additional], axis=1)
# Identical:
# new = pandas.concat([original, additional], ignore_index=False, axis=1)
print(new.head())
# Age Gender Name
#0 10 M Nate A
#1 12 F Jessie A
#2 13 F Daniel H
#3 NaN NaN John D
請注意 John D 是如何沒有 Age 或 Gender 的。
使用 concat 並傳遞axis=1
和ignore_index=True
:
In [38]:
import numpy as np
df = pd.DataFrame({'a':np.arange(5)})
df1 = pd.DataFrame({'b':np.arange(4)})
print(df1)
df
b
0 0
1 1
2 2
3 3
Out[38]:
a
0 0
1 1
2 2
3 3
4 4
In [39]:
pd.concat([df,df1], ignore_index=True, axis=1)
Out[39]:
0 1
0 0 0
1 1 1
2 2 2
3 3 3
4 4 NaN
我們可以將不同大小的列表值添加到 DataFrame。
例子
a = [0,1,2,3]
b = [0,1,2,3,4,5,6,7,8,9]
c = [0,1]
查找所有列表的長度
la,lb,lc = len(a),len(b),len(c)
# now find the max
max_len = max(la,lb,lc)
根據確定的最大長度調整所有大小(不在此示例中
if not max_len == la:
a.extend(['']*(max_len-la))
if not max_len == lb:
b.extend(['']*(max_len-lb))
if not max_len == lc:
c.extend(['']*(max_len-lc))
現在所有列表的長度相同並創建數據框
pd.DataFrame({'A':a,'B':b,'C':c})
最終輸出是
A B C
0 1 0 1
1 2 1
2 3 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9
我有同樣的問題,兩個不同的數據框,沒有一個公共列。 我只需要將它們並排放在一個 csv 文件中。
df1 = df1.reset_index()
df2 = df2.reset_index()
df = [df1, df2]
df_final = pd.concat(df, axis=1)
df_final.to_csv(filename, index=False)
這樣,你會看到你的dfs
彼此dfs
(按列),每個都有自己的長度。
如果有人喜歡替換不同大小的特定列而不是添加它。
基於這個答案,我使用 dict 作為中間類型。 使用不同大小的列創建 Pandas Dataframe
如果要插入的列不是列表而是已經是字典,則可以省略相應的行。
def fill_column(dataframe: pd.DataFrame, list: list, column: str):
dict_from_list = dict(enumerate(list)) # create enumertable object from list and create dict
dataFrame_asDict = dataframe.to_dict() # Get DataFrame as Dict
dataFrame_asDict[column] = dict_from_list # Assign specific column
return pd.DataFrame.from_dict(dataFrame_asDict, orient='index').T # Create new DataSheet from Dict and return it
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.