【问题标题】:Pandas - Pivot, Stack, Unstack?熊猫 - 枢轴,堆叠,取消堆叠?
【发布时间】:2019-01-08 07:27:11
【问题描述】:

我想知道如何让键成为列标题(结果、IP、时间)?

CSV 中的数据如下所示:

"Result":"Success","IP":"0.0.0.0","time":"2018-08-20T12:00:00.000Z"
"Result":"Failure","IP":"1.1.1.1","time":"2018-08-20T12:01:00.000Z"

我想这样格式化:

Result        IP        time
Success    0.0.0.0    2018-08-20T12:00:00.000Z
Failure    1.1.1.1    2018-08-20T12:01:00.000Z

到目前为止我的代码:

import pandas as pd
file = pd.read_csv("path_to.csv", sep='\n', names = ["Result","IP","time"])
df = pd.DataFrame(file)
print(df.head(1))

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    你需要:

    import csv
    file = pd.read_csv("foo.csv", sep=',', header=None, quoting=csv.QUOTE_ALL, names=["Result", "IP", "time"])
    df = pd.DataFrame(file)
    df = df.applymap(lambda x: (''.join(str(x).split(":")[1:]))[1:-1])
    

    输出:

        Result       IP                    time
    0  Success  0.0.0.0  2018-08-20T120000.000Z
    1  Failure  1.1.1.1  2018-08-20T120100.000Z
    

    【讨论】:

    • 优秀。现在我只需要找出为什么这些值会偏移到左边一列。例如0.0.0.0 显示在 Result 下,2018-08-20T12:00:00.000Z 显示在 IP 下。
    【解决方案2】:

    这是一种类似的方法,也使用str.split,但它通过拆分正则表达式来保留您的时区信息,该正则表达式比仅拆分:更具选择性(它仅在:前面有2时才拆分或更多字母):

    df = pd.read_csv('data.csv', header=None, sep=',', names=['Result', 'IP', 'Time'])
    
    new_df = df.apply(lambda x: x.str.split('[A-Za-z]{2,}:').str[1].str.strip('\"'))
    
    >>> new_df
        Result       IP                      Time
    0  Success  0.0.0.0  2018-08-20T12:00:00.000Z
    1  Failure  1.1.1.1  2018-08-20T12:01:00.000Z
    

    【讨论】:

    • 谢谢!也为您的答案 +1(相同基本策略的不同变体)
    猜你喜欢
    • 1970-01-01
    • 2021-12-05
    • 1970-01-01
    • 2021-09-10
    • 1970-01-01
    • 1970-01-01
    • 2019-08-05
    • 1970-01-01
    相关资源
    最近更新 更多