![](/img/trans.png)
[英]Appending a pandas.DataFrame to one column of another pandas.DataFrame
[英]Assign pandas.DataFrame column To Series with Default
假設我有一個DataFrame
df = pandas.DataFrame({'a': [1,2], 'b': [3,4]}, ['foo', 'bar'])
a b
foo 1 3
bar 2 4
我想添加一個基於另一個Series
的列:
s = pandas.Series({'foo': 10, 'baz': 20})
foo 10
baz 20
dtype: int64
如果DataFrame索引值不在Series索引中,如何將Series分配給DataFrame的列並提供默認值?
我正在尋找某種形式的東西:
df['c'] = s.withDefault(42)
這將導致以下數據框:
a b c
foo 1 3 10
bar 2 4 42
#Note: bar got value 42 because it's not in s
預先感謝您的考慮和回應。
map
與get
get
具有可用於指定默認值的參數。
df.assign(c=df.index.map(lambda x: s.get(x, 42)))
a b c
foo 1 3 10
bar 2 4 42
reindex
與fill_value
一起fill_value
df.assign(c=s.reindex(df.index, fill_value=42))
a b c
foo 1 3 10
bar 2 4 42
您需要在df
和從s
獲取的數據幀之間使用join ,然后在您的情況下用默認值(即42)填充NaN
。
df['c'] = df.join(pandas.DataFrame(s, columns=['c']))['c'].fillna(42).astype(int)
輸出:
a b c
foo 1 3 10
bar 2 4 42
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.