[英]Error when setting default value to entire new column in Pandas dataframe
[英]python pandas dataframe: Creating new column with default value, when default value is an iterable
我有一個熊貓數據框,如下所示:
In [1]: import pandas as pd
In [2]: df = pd.DataFrame([[1,2],[3,4],[5,6]], columns=['a','b'])
In [3]: print df
Out [3]:
a b
0 1 2
1 3 4
2 5 6
現在,我想添加一個默認值作為字典的新列“ c”。 結果數據框應如下所示:
a b c
0 1 2 {1: 2, 3: 4}
1 3 4 {1: 2, 3: 4}
2 5 6 {1: 2, 3: 4}
我嘗試了以下方法:
df.at[:, 'c'] = {1: 2, 3: 4}
ValueError: Length of values does not match length of index
和
df['c'] = {1: 2, 3: 4}
ValueError: Must have equal len keys and value when setting with an iterable
這個對我有用
df['c'] = df.apply(lambda x: {1:2, 3:4}, axis=1)
但是看起來很骯臟。 有沒有更清潔的方法可以做到這一點?
在DF中有三行,而在dict中只有兩個元素,請執行以下操作:
c = {0:1,1:1,2:2}
df['c'] = c
輸出:
a b c
0 1 2 0
1 3 4 1
2 5 6 2
要在數據框中重復使用相同的字典,您需要創建此類字典的列表
c = {1:2,3:4}
c = [c]*3
df['c'] = c
產量
a b c
0 1 2 {1: 2, 3: 4}
1 3 4 {1: 2, 3: 4}
2 5 6 {1: 2, 3: 4}
可能但不建議將DataFrame
存儲在DataFrame
列中,因為不能使用所有矢量化的熊貓函數:
df['c'] = [{1: 2, 3: 4} for x in np.arange(len(df))]
print (df)
a b c
0 1 2 {1: 2, 3: 4}
1 3 4 {1: 2, 3: 4}
2 5 6 {1: 2, 3: 4}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.