类型错误:字符串索引必须为整数

时间:2019-03-01 09:40:40

标签: python pandas

import pandas as pd
def city_data():

    city = {'City' : pd.Series(['Ithaca', 'Willingboro', 'Holyoke', 'Abilene', 'New York']),
        'Shape Reported': pd.Series(['Triangle', 'Other', 'Oval', 'Disk', 'Light']), 
        'State': pd.Series(['NY', 'NJ', 'CO', 'KS', 'NY']), 
       'Start Time': pd.Series(['6/1/1930 22:00', '6/30/1930 20:00', '2/15/1931 13:00', '6/1/1931 13:00', '4/18/1933 19:00' ])}
    df = pd.DataFrame(city)
    df['Start Time'] = pd.to_datetime(df['Start Time'])
    return df

def time(df):
    df['month'] = df['Start Time'].dt.month
    common_month = df['month'].mode()
    print(common_month)
time(df)  

当我在数据框上方运行时,它显示错误字符串索引必须为整数。 我不知道如何解决这个问题。

2 个答案:

答案 0 :(得分:0)

时间呼叫

之前添加 df 初始化

`df = city_data()

时间(df) `

在这种情况下,我可以看到如下输出:

0 6

dtype:int64

答案 1 :(得分:0)

您的代码存在的问题是df最初不存在。您已经创建了city_data(),但没有调用它:

尝试以下代码:

import pandas as pd
def city_data():

    city = {'City' : pd.Series(['Ithaca', 'Willingboro', 'Holyoke', 'Abilene', 'New York']),
    'Shape Reported': pd.Series(['Triangle', 'Other', 'Oval', 'Disk', 'Light']),
    'State': pd.Series(['NY', 'NJ', 'CO', 'KS', 'NY']),
        'Start Time': pd.Series(['6/1/1930 22:00', '6/30/1930 20:00', '2/15/1931 13:00', '6/1/1931 13:00', '4/18/1933 19:00' ])}
     df = pd.DataFrame(city)
     df['Start Time'] = pd.to_datetime(df['Start Time'])
     return df

def time(df):
     df['month'] = df['Start Time'].dt.month
     common_month = df['month'].mode()
     print(common_month)

df = city_data() # Call city_data
print(df)
time(df) # Pass returned data to time

输出:

          City Shape Reported          Start Time State
0       Ithaca       Triangle 1930-06-01 22:00:00    NY
1  Willingboro          Other 1930-06-30 20:00:00    NJ
2      Holyoke           Oval 1931-02-15 13:00:00    CO
3      Abilene           Disk 1931-06-01 13:00:00    KS
4     New York          Light 1933-04-18 19:00:00    NY
0    6
dtype: int64

希望这能回答您的问题!