import pandas as pd
a = [['a', 1, 2, 3], ['b', 4, 5, 6], ['c', 7, 8, 9]]
df = pd.DataFrame(a, columns=['alpha', 'one', 'two', 'three'])
df.set_index(['alpha'], inplace = True)
one two three
alpha
a 1 2 3
b 4 5 6
c 7 8 9
我想設定一些值,例如:
df.loc['a']['one'] = 1000
當索引不存在時,我們用這個索引添加一個新行而不檢查是否存在,就像字典一樣(如果鍵不存在dict[new key]將自動創建這個鍵)。例如:
df.loc['d']['three'] = 999
然后會有一個新行:
d: Nan, Nan, 999
以下代碼對我不起作用:
df.loc['d']['three'] = 999

uj5u.com熱心網友回復:
這正是 pandas 所做的,但您需要loc正確使用索引器:
df.loc['a', 'one'] = 1000
df.loc['d', 'three'] = 999
輸出:
one two three
alpha
a 1000.0 2.0 3.0
b 4.0 5.0 6.0
c 7.0 8.0 9.0
d NaN NaN 999.0
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/474501.html
