How can pandas assign values to one column based on another column?

To assign values from one column to another column in Pandas, you can use the .loc method. Below is an example illustrating how to assign values to another column based on the values in one column.

import pandas as pd

# 创建一个示例DataFrame
data = {'A': [1, 2, 3, 4, 5],
        'B': [6, 7, 8, 9, 10]}
df = pd.DataFrame(data)

# 根据列'A'的值,将列'B'的值设置为新的值
df.loc[df['A'] > 3, 'B'] = 0

print(df)

The output is as follows:

   A  B
0  1  6
1  2  7
2  3  8
3  4  0
4  5  0

In the example above, we first created a DataFrame with two columns. Then, we used the .loc method to select rows where the value in column ‘A’ is greater than 3 and set the value in column ‘B’ to 0.

Please note that this method will directly modify the original DataFrame without creating a new DataFrame. If you want to create a new DataFrame without altering the original one, you can use the .copy() method to create a copy of the DataFrame and then perform operations on the copy.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds