Jia*_* Li 72
对于混合位置和索引,请使用.ix.但是你需要确保你的索引不是整数,否则会引起混淆.
df.ix[0, 'COL_NAME'] = x
Run Code Online (Sandbox Code Playgroud)
或者,试试吧
df.iloc[0, df.columns.get_loc('COL_NAME')] = x
Run Code Online (Sandbox Code Playgroud)
例:
import pandas as pd
import numpy as np
# your data
# ========================
np.random.seed(0)
df = pd.DataFrame(np.random.randn(10, 2), columns=['col1', 'col2'], index=np.random.randint(1,100,10)).sort_index()
print(df)
col1 col2
10 1.7641 0.4002
24 0.1440 1.4543
29 0.3131 -0.8541
32 0.9501 -0.1514
33 1.8676 -0.9773
36 0.7610 0.1217
56 1.4941 -0.2052
58 0.9787 2.2409
75 -0.1032 0.4106
76 0.4439 0.3337
# .iloc with get_loc
# ===================================
df.iloc[0, df.columns.get_loc('col2')] = 100
df
col1 col2
10 1.7641 100.0000
24 0.1440 1.4543
29 0.3131 -0.8541
32 0.9501 -0.1514
33 1.8676 -0.9773
36 0.7610 0.1217
56 1.4941 -0.2052
58 0.9787 2.2409
75 -0.1032 0.4106
76 0.4439 0.3337
Run Code Online (Sandbox Code Playgroud)
for*_*ect 22
我在这里要补充的一点是,at数据帧上的函数要快得多,特别是如果你要对单个(非切片)值进行大量赋值.
df.at[index, 'col_name'] = x
Run Code Online (Sandbox Code Playgroud)
根据我的经验,我获得了20倍的加速.这是一个西班牙语的写作,但仍然给人一种正在发生的事情的印象.
如果你知道这个位置,为什么不从中得到索引呢?
然后使用.loc:
df.loc[index, 'COL_NAME'] = x
Run Code Online (Sandbox Code Playgroud)
您可以使用:
df.set_value('Row_index', 'Column_name', value)
Run Code Online (Sandbox Code Playgroud)
set_valye比.ix方法快100倍 然后使用它也更好 df['Row_index']['Column_name'] = value。
但是由于现在已set_value被弃用,所以.iat/ .at是好的替代品。
例如,如果我们有此data_frame
A B C
0 1 8 4
1 3 9 6
2 22 33 52
Run Code Online (Sandbox Code Playgroud)
如果我们要修改单元格[0,“ A”]的值,我们可以做
df.iat[0,0] = 2
Run Code Online (Sandbox Code Playgroud)
要么 df.at[0,'A'] = 2
另一种方法是,根据行的索引位置为给定行分配列值,索引位置始终从零开始,最后一个索引位置是数据帧的长度:
df["COL_NAME"].iloc[0]=x
Run Code Online (Sandbox Code Playgroud)
修改“r”行(“A”列)和“C”列交叉处的单元格中的值
检索“A”列中“r”行的索引
i = df[ df['A']=='r' ].index.values[0]
Run Code Online (Sandbox Code Playgroud)修改所需列“C”中的值
df.loc[i,"C"]="newValue"
Run Code Online (Sandbox Code Playgroud)注意:在此之前,请务必重置行索引...以获得一个漂亮的索引列表!
df=df.reset_index(drop=True)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
104044 次 |
| 最近记录: |