这个框架看起来像这样:| 年|月|| --|--|| 2021 | 10 || 2021 | 11 || 2021 | 12 || 2022 | 1 || 2022 | 2 || 2022 | 3 || 楠| 1 |我必须通过检查相应月份列的年份来填充年份列中的空值,即如果月份是1,2或3,那么年份应该是2022,或者如果月份是10,11或12,那么年份应该是2021。在这个例子中,我需要用2022来填充年的NaN值。使用pandas解决这个问题的最好方法是什么?
1cklez4t1#
你可以使用布尔索引和numpy.select:
numpy.select
m = df['Year'].isna()df.loc[m, 'Year'] = np.select([df.loc[m, 'Month'].between(1, 3), df.loc[m, 'Month'].between(10, 12)], [2022, 2021])# if you want integersdf = df.convert_dtypes()
m = df['Year'].isna()
df.loc[m, 'Year'] = np.select([df.loc[m, 'Month'].between(1, 3),
df.loc[m, 'Month'].between(10, 12)],
[2022, 2021])
# if you want integers
df = df.convert_dtypes()
字符串输出量:
Year Month0 2021 101 2021 112 2021 123 2022 14 2022 25 2022 36 2022 1
Year Month
0 2021 10
1 2021 11
2 2021 12
3 2022 1
4 2022 2
5 2022 3
6 2022 1
型
wn9m85ua2#
验证码
使用map和fillna
map
fillna
m = {1:2022, 2:2022, 3:2022, 10:2021, 11:2021, 12:2021}out = df.assign(Year=df['Year'].fillna(df['Month'].map(m)).astype('int'))
m = {1:2022, 2:2022, 3:2022, 10:2021, 11:2021, 12:2021}
out = df.assign(Year=df['Year'].fillna(df['Month'].map(m)).astype('int'))
字符串输出:
示例代码
import pandas as pddata1 = {'Year': [2021, 2021, 2021, 2022, 2022, 2022, None], 'Month': [10, 11, 12, 1, 2, 3, 1]}df = pd.DataFrame(data1)
import pandas as pd
data1 = {'Year': [2021, 2021, 2021, 2022, 2022, 2022, None],
'Month': [10, 11, 12, 1, 2, 3, 1]}
df = pd.DataFrame(data1)
2条答案
按热度按时间1cklez4t1#
你可以使用布尔索引和
numpy.select
:字符串
输出量:
型
wn9m85ua2#
验证码
使用
map
和fillna
字符串
输出:
型
示例代码
型