简体   繁体   中英

Pandas - Replace values based on index condition to different values

If I create a dataframe like so:

 import pandas as pd, numpy as np
 df = pd.DataFrame(np.random.randint(0,100,size=(100, 2)), columns=list('AB'))
 replace_1=[i+random.randint(0, 50) for i in range(16)]

How would I change the entry in column A to be the values of replace_1 list from row 0 -15, for example? In other words, how do I replace specific cells value from a list of value based purely on index?

here is one way to do it

# update the column in DF with series, based on the index value
df['A'].update(replace_1)

result

    A   B
0   7   17
1   26  70
2   13  81
3   48  64
4   45  74
...     ...     ...
95  74  3
96  18  94
97  81  4
98  37  11
99  65  29

replace_1

[7, 26, 13, 48, 45, 51, 35, 53, 20, 11, 38, 16, 36, 14, 63, 24]

Starting DF

    A   B
0   75  17
1   84  70
2   57  81
3   88  64
4   78  74
...     ...     ...
95  74  3
96  18  94
97  81  4
98  37  11
99  65  29

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM