[英]How to change values in certain column of DataFrame based on another DataFrame in Pandas
[英]How to edit the values in one column when a certain value is realised in another in pandas DataFrame?
我有以下 DataFrame 以及此處包含的幾列:
Col2 Col3 Col4
0 3682 US91892 US
1 7568 US91234 US
2 3546 UKIPD GB
3 7892 UKI43 GB
4 1243 US92345 US
為此,如果 col4 = US 我只想獲取 col3 的最后 5 位數字,例如:
Col2 Col3 Col4
0 3682 91892 US
1 7568 91234 US
2 3546 UKIPD GB
3 7892 UKI43 GB
4 1243 92345 US
為此,我嘗試過:
for a in df.index:
if df["col4"][a] == "US":
df["col3"][a] = df["col3"][a][-5:]
但是,它需要幾個小時才能運行(數據集大約有 170,000 個數據點,其中有幾個這樣的數據集)。 我想知道是否有更快更有效的方法來做到這一點?
另一種方法是使用 boolean 索引:
df.loc[df.Col4=='US', 'Col3'] = df.Col3.str[-5:]
Output:
Col2 Col3 Col4
0 3682 91892 US
1 7568 91234 US
2 3546 UKIPD GB
3 7892 UKI43 GB
4 1243 92345 US
你可以試試:
df['Col3'] = df['Col3'].str[-5:].where(df['Col4'].eq('US'),df['Col3'])
#or df['Col3'] = np.where(df['Col4'].eq('US'),df['Col3'].str[-5:],df['Col3'])
print(df)
Col2 Col3 Col4
0 3682 91892 US
1 7568 91234 US
2 3546 UKIPD GB
3 7892 UKI43 GB
4 1243 92345 US
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.