0
有a question on SO with the title "Set value for particular cell in pandas DataFrame",但它假定行索引已知。如果相關列中的行值是唯一的,我該如何更改值?是最簡單的選項使用set_index?以index.tolist返回索引值列表似乎不是一個非常優雅的解決方案。當索引未知並且列中的值是唯一的時,替換熊貓數據幀中的單個值
這裏是我的代碼:
import pandas as pd
## Fill the data frame.
df = pd.DataFrame([[1, 2], [3, 4]], columns=('a', 'b'))
print(df, end='\n\n')
## Just use the index, if we know it.
index = 0
df.set_value(index, 'a', 5)
print('set_value', df, sep='\n', end='\n\n')
## Define a new index column.
df.set_index('a', inplace=True)
print('set_index', df, sep='\n', end='\n\n')
## Use the index values of column A, which are known to us.
index = 3
df.set_value(index, 'b', 6)
print('set_value', df, sep='\n', end='\n\n')
## Reset the index.
df.reset_index(inplace = True)
print('reset_index', df, sep='\n')
這裏是我的輸出:
a b
0 1 2
1 3 4
set_value
a b
0 5 2
1 3 4
set_index
b
a
5 2
3 4
set_value
b
a
5 2
3 6
reset_index
a b
0 5 2
1 3 6
謝謝!我剛剛在其他問題線程中找到了相同的答案。它只有很少的選票。 https://stackoverflow.com/a/38467449/778533 –
@ tommy.carstensen這是一個非常近期的答案,幾乎在問題提出四年後才被問到。 :) – Psidom