Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/364.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 数据帧列中的意外赋值_Python_Pandas_Dataframe - Fatal编程技术网

Python 数据帧列中的意外赋值

Python 数据帧列中的意外赋值,python,pandas,dataframe,Python,Pandas,Dataframe,我用pandas dataframe模拟数据,代码如下: import pandas as pd from random import randrange df = pd.DataFrame() df['YYYYMM'] = pd.Series(3*list(pd.date_range(start="1/1/2019", end="12/1/2020", freq="MS"))) df['Regions'] = pd.Series([

我用pandas dataframe模拟数据,代码如下:

import pandas as pd
from random import randrange

df = pd.DataFrame()
df['YYYYMM'] = pd.Series(3*list(pd.date_range(start="1/1/2019", end="12/1/2020", freq="MS")))
df['Regions'] = pd.Series(['NA', 'EMEA', 'APAC']).repeat(24).reset_index()[0]

df_emea = df[df['Regions'] == 'EMEA'].copy()
df_emea["YYYYMM"] = df_emea["YYYYMM"].repeat(3).reset_index()['YYYYMM']
df_emea["country"] = pd.Series(24*['UK', 'Germany', 'France']).reset_index()[0]

df_na = df[df['Regions'] == 'NA'].copy()
df_na["YYYYMM"] = df_na["YYYYMM"].repeat(2).reset_index()['YYYYMM']
df_na["Country"] = pd.Series(24*['Canada', 'USA']).reset_index()[0]

df_apac = df[df['Regions'] == 'APAC'].copy()
df_apac["YYYYMM"] = df_apac["YYYYMM"].repeat(2).reset_index()['YYYYMM']
df_apac["Country"] = pd.Series(24*['China', 'Japan']).reset_index()[0]
除了df_apac之外,一切正常。不知何故,我在
Country
列中有
None
,在
YYYYMM
列中有NaT:


有人能解释为什么会这样吗?

你有索引问题。由于没有重置初始df_xxx数据帧的索引,因此它们保留了初始数据帧中的索引。因此,当您稍后尝试添加新列时,索引未对齐

因此,快速解决方法是使用:

df_emea = df[df['Regions'] == 'EMEA'].copy().reset_index(drop=True)
...
df_na = df[df['Regions'] == 'NA'].copy().reset_index(drop=True)
...
df_apac = df[df['Regions'] == 'APAC'].copy().reset_index(drop=True)
...

我现在给出了
df_-apac
的预期结果,但对于
df_-emea
您仍然只能看到48行,其中需要72行才能接受3个国家。但它可能满足您的要求…

从第四行代码中删除
freq=“MS”
参数。@etch_45,谢谢您的评论,我为什么要删除它?它代表月初。很有趣。这看起来像是一个类似于前一段时间的bug,它还涉及到
df.reset\u index
和数据损坏。谢谢,这对我很有帮助。