Loading [MathJax]/jax/output/CommonHTML/config.js
前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >[Asp.Net Core] 网站中的XSS跨站脚本攻击和防范

[Asp.Net Core] 网站中的XSS跨站脚本攻击和防范

作者头像
郑子铭
发布于 2023-08-29 02:58:34
发布于 2023-08-29 02:58:34
30701
代码可运行
举报
运行总次数:1
代码可运行

漏洞说明: 跨站脚本攻击(Cross Site Scripting),为了不和层叠样式表(Cascading Style Sheets, CSS)的缩写混淆,故将跨站脚本攻击缩写为XSS。恶意攻击者往Web页面里插入恶意Web脚本代码(html、javascript、css等),当用户浏览该页面时,嵌入其中的Web脚本代码会被执行,从而达到恶意攻击用户的特殊目的。

测试步骤 访问系统网站,点击基础报告库进行编辑,使用Burp抓包并重新构造数据包

重新访问,成功触发了XSS弹窗

解决方法:

将危险内容过滤去除,用HTML转义字符串(Escape Sequence)表达的则保留 添加脚本过滤类

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
    /// <summary>
    /// Html 脚本过滤
    /// </summary>
    public class NHtmlFilter
    {
        protected static readonly RegexOptions REGEX_FLAGS_SI = RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.Compiled;

        private static string P_COMMENTS = "<!--(.*?)-->";
        private static Regex P_COMMENT = new Regex("^!--(.*)--$", REGEX_FLAGS_SI);
        private static string P_TAGS = "<(.*?)>";
        private static Regex P_END_TAG = new Regex("^/([a-z0-9]+)", REGEX_FLAGS_SI);
        private static Regex P_START_TAG = new Regex("^([a-z0-9]+)(.*?)(/?)$", REGEX_FLAGS_SI);
        private static Regex P_QUOTED_ATTRIBUTES = new Regex("([a-z0-9|(a-z0-9\\-a-z0-9)]+)=([\"'])(.*?)\\2", REGEX_FLAGS_SI);
        private static Regex P_UNQUOTED_ATTRIBUTES = new Regex("([a-z0-9]+)(=)([^\"\\s']+)", REGEX_FLAGS_SI);
        private static Regex P_PROTOCOL = new Regex("^([^:]+):", REGEX_FLAGS_SI);
        private static Regex P_ENTITY = new Regex("&#(\\d+);?");
        private static Regex P_ENTITY_UNICODE = new Regex("&#x([0-9a-f]+);?");
        private static Regex P_ENCODE = new Regex("%([0-9a-f]{2});?");
        private static Regex P_VALID_ENTITIES = new Regex("&([^&;]*)(?=(;|&|$))");
        private static Regex P_VALID_QUOTES = new Regex("(>|^)([^<]+?)(<|$)", RegexOptions.Singleline | RegexOptions.Compiled);
        private static string P_END_ARROW = "^>";
        private static string P_BODY_TO_END = "<([^>]*?)(?=<|$)";
        private static string P_XML_CONTENT = "(^|>)([^<]*?)(?=>)";
        private static string P_STRAY_LEFT_ARROW = "<([^>]*?)(?=<|$)";
        private static string P_STRAY_RIGHT_ARROW = "(^|>)([^<]*?)(?=>)";
        private static string P_AMP = "&";
        private static string P_QUOTE = "\"";
        private static string P_LEFT_ARROW = "<";
        private static string P_RIGHT_ARROW = ">";
        private static string P_BOTH_ARROWS = "<>";

        // @xxx could grow large... maybe use sesat's ReferenceMap
        private static Dictionary<string, string> P_REMOVE_PAIR_BLANKS = new Dictionary<string, string>();
        private static Dictionary<string, string> P_REMOVE_SELF_BLANKS = new Dictionary<string, string>();
        /** 
         * flag determining whether to try to make tags when presented with "unbalanced"
         * angle brackets (e.g. "<b text </b>" becomes "<b> text </b>").  If set to false,
         * unbalanced angle brackets will be html escaped.
         */
        protected static bool alwaysMakeTags = true;

        /**
         * flag determing whether comments are allowed in input String.
         */
        protected static bool stripComment = true;


        /// <summary>
        /// 不允许
        /// </summary>
        private string[] vDisallowed { get; set; }
        /// <summary>
        /// 允许
        /// </summary>
        protected Dictionary<string, List<string>> vAllowed { get; set; }

        /** counts of open tags for each (allowable) html element **/
        protected Dictionary<string, int> vTagCounts;

        /** html elements which must always be self-closing (e.g. "<img />") **/
        protected string[] vSelfClosingTags;

        /** html elements which must always have separate opening and closing tags (e.g. "<b></b>") **/
        protected string[] vNeedClosingTags;

        /** attributes which should be checked for valid protocols **/
        protected string[] vProtocolAtts;

        /** allowed protocols **/
        protected string[] vAllowedProtocols;

        /** tags which should be removed if they contain no content (e.g. "<b></b>" or "<b />") **/
        protected string[] vRemoveBlanks;

        /** entities allowed within html markup **/
        protected string[] vAllowedEntities;


        /// <summary>
        /// 是否为调试
        /// </summary>
        protected bool vDebug;

        public NHtmlFilter() : this(false) { }

        public NHtmlFilter(bool debug)
        {
            //List<Item> vAllowed = new List<Item>();
            vAllowed = new Dictionary<string, List<string>>();
            #region 允许通过数组

            vAllowed.Add("a", new List<string>() { "target", "href", "title", "class", "style" });
            vAllowed.Add("addr", new List<string>() { "title", "class", "style" });
            vAllowed.Add("address", new List<string>() { "class", "style" });
            vAllowed.Add("area", new List<string>() { "shape", "coords", "href", "alt" });
            vAllowed.Add("article", new List<string>() { });
            vAllowed.Add("aside", new List<string>() { });
            vAllowed.Add("audio", new List<string>() { "autoplay", "controls", "loop", "preload", "src", "class", "style" });
            vAllowed.Add("b", new List<string>() { "class", "style" });
            vAllowed.Add("bdi", new List<string>() { "dir" });
            vAllowed.Add("bdo", new List<string>() { "dir" });
            vAllowed.Add("big", new List<string>() { });
            vAllowed.Add("blockquote", new List<string>() { "cite", "class", "style" });
            vAllowed.Add("br", new List<string>() { });
            vAllowed.Add("caption", new List<string>() { "class", "style" });
            vAllowed.Add("center", new List<string>() { });
            vAllowed.Add("cite", new List<string>() { });
            vAllowed.Add("code", new List<string>() { "class", "style" });
            vAllowed.Add("col", new List<string>() { "align", "valign", "span", "width", "class", "style" });
            vAllowed.Add("colgroup", new List<string>() { "align", "valign", "span", "width", "class", "style" });
            vAllowed.Add("dd", new List<string>() { "class", "style" });
            vAllowed.Add("del", new List<string>() { "datetime" });
            vAllowed.Add("details", new List<string>() { "open" });
            vAllowed.Add("div", new List<string>() { "class", "style" });
            vAllowed.Add("dl", new List<string>() { "class", "style" });
            vAllowed.Add("dt", new List<string>() { "class", "style" });
            vAllowed.Add("em", new List<string>() { "class", "style" });
            vAllowed.Add("font", new List<string>() { "color", "size", "face" });
            vAllowed.Add("footer", new List<string>() { });
            vAllowed.Add("h1", new List<string>() { "class", "style" });
            vAllowed.Add("h2", new List<string>() { "class", "style" });
            vAllowed.Add("h3", new List<string>() { "class", "style" });
            vAllowed.Add("h4", new List<string>() { "class", "style" });
            vAllowed.Add("h5", new List<string>() { "class", "style" });
            vAllowed.Add("h6", new List<string>() { "class", "style" });
            vAllowed.Add("header", new List<string>() { });
            vAllowed.Add("hr", new List<string>() { });
            vAllowed.Add("i", new List<string>() { "class", "style" });
            vAllowed.Add("img", new List<string>() { "src", "alt", "title", "style", "width", "height", "id", "_src", "loadingclass", "class", "data-latex", "data-id", "data-type", "data-s" });
            vAllowed.Add("ins", new List<string>() { "datetime" });
            vAllowed.Add("li", new List<string>() { "class", "style" });
            vAllowed.Add("mark", new List<string>() { });
            vAllowed.Add("nav", new List<string>() { });
            vAllowed.Add("ol", new List<string>() { "class", "style" });
            vAllowed.Add("p", new List<string>() { "class", "style" });
            vAllowed.Add("pre", new List<string>() { "class", "style" });
            vAllowed.Add("s", new List<string>() { });
            vAllowed.Add("section", new List<string>() { });
            vAllowed.Add("small", new List<string>() { });
            vAllowed.Add("span", new List<string>() { "class", "style" });
            vAllowed.Add("sub", new List<string>() { "class", "style" });
            vAllowed.Add("sup", new List<string>() { "class", "style" });
            vAllowed.Add("strong", new List<string>() { "class", "style" });
            vAllowed.Add("table", new List<string>() { "width", "border", "align", "valign", "class", "style" });
            vAllowed.Add("tbody", new List<string>() { "align", "valign", "class", "style" });
            vAllowed.Add("td", new List<string>() { "width", "rowspan", "colspan", "align", "valign", "class", "style" });
            vAllowed.Add("tfoot", new List<string>() { "align", "valign", "class", "style" });
            vAllowed.Add("th", new List<string>() { "width", "rowspan", "colspan", "align", "valign", "class", "style" });
            vAllowed.Add("thead", new List<string>() { "align", "valign", "class", "style" });
            vAllowed.Add("tr", new List<string>() { "rowspan", "align", "valign", "class", "style" });
            vAllowed.Add("tt", new List<string>() { });
            vAllowed.Add("u", new List<string>() { });
            vAllowed.Add("ul", new List<string>() { "class", "style" });
            vAllowed.Add("video", new List<string>() { "autoplay", "controls", "loop", "preload", "src", "height", "width", "class", "style" });
            #endregion


            vDebug = debug;
            vTagCounts = new Dictionary<string, int>();

            vSelfClosingTags = new string[] { "img" };
            vNeedClosingTags = new string[] { "a", "b", "strong", "i", "em" };
            vDisallowed = new string[] { "script" };
            vAllowedProtocols = new string[] { "http", "mailto" }; // no ftp.
            vProtocolAtts = new string[] { "src", "href" };
            vRemoveBlanks = new string[] { "a", "b", "strong", "i", "em" };
            vAllowedEntities = new string[] { "amp", "gt", "lt", "quot" };
            stripComment = true;
            alwaysMakeTags = true;
        }


        protected void reset()
        {
            vTagCounts = new Dictionary<string, int>();
        }

        protected void debug(string msg)
        {
            if (vDebug)
                System.Diagnostics.Debug.WriteLine(msg);
        }

        //---------------------------------------------------------------
        // my versions of some PHP library functions

        public static string chr(int dec)
        {
            return "" + (char)dec;
        }

        /// <summary>
        /// 转换成实体字符
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string htmlSpecialChars(string str)
        {
            str = str.Replace(P_QUOTE, "\"");

            str = str.Replace(P_LEFT_ARROW, "<");
            str = str.Replace(P_RIGHT_ARROW, ">");
            str = str.Replace("\n", "<br>");
            return str;
        }

        //---------------------------------------------------------------

        /**
         * given a user submitted input String, filter out any invalid or restricted
         * html.
         * 
         * @param input text (i.e. submitted by a user) than may contain html
         * @return "clean" version of input, with only valid, whitelisted html elements allowed
         */
        public string filter(string input)
        {
            reset();
            string s = input;

            debug("************************************************");
            debug("              INPUT: " + input);

            s = escapeComments(s);
            debug("     escapeComments: " + s);

            s = balanceHTML(s);
            debug("        balanceHTML: " + s);

            s = checkTags(s);
            debug("          checkTags: " + s);

            s = processRemoveBlanks(s);
            debug("processRemoveBlanks: " + s);

            s = validateEntities(s);
            debug("    validateEntites: " + s);

            debug("************************************************\n\n");
            return s;
        }

        protected string escapeComments(string s)
        {
            return Regex.Replace(s, P_COMMENTS, new MatchEvaluator(ConverMatchComments), RegexOptions.Singleline);
        }

        protected string regexReplace(string regex_pattern, string replacement, string s)
        {
            return Regex.Replace(s, regex_pattern, replacement);
        }

        protected string balanceHTML(string s)
        {
            if (alwaysMakeTags)
            {
                //
                // try and form html
                //
                s = regexReplace(P_END_ARROW, "", s);
                s = regexReplace(P_BODY_TO_END, "<$1>", s);
                s = regexReplace(P_XML_CONTENT, "$1<$2", s);

            }
            else
            {
                //
                // escape stray brackets
                //
                s = regexReplace(P_STRAY_LEFT_ARROW, "<$1", s);
                s = regexReplace(P_STRAY_RIGHT_ARROW, "$1$2><", s);

                //
                // the last regexp causes '<>' entities to appear
                // (we need to do a lookahead assertion so that the last bracket can
                // be used in the next pass of the regexp)
                //
                s = s.Replace(P_BOTH_ARROWS, "");
            }
            return s;
        }

        protected string checkTags(string s)
        {
            //替换不允许标签
            foreach (var item in vDisallowed)
            {
                s = Regex.Replace(s, string.Format(@"<{0}\b(.)*?>(.)+?</{0}>", item), "");
            }
            s = Regex.Replace(s, P_TAGS, new MatchEvaluator(ConverMatchTags), RegexOptions.Singleline);

            // these get tallied in processTag
            // (remember to reset before subsequent calls to filter method)
            foreach (string key in vTagCounts.Keys)
            {
                for (int ii = 0; ii < vTagCounts[key]; ii++)
                {
                    s += "</" + key + ">";
                }
            }

            return s;
        }

        protected string processRemoveBlanks(string s)
        {
            foreach (string tag in vRemoveBlanks)
            {
                s = regexReplace("<" + tag + "(\\s[^>]*)?></" + tag + ">", "", s);
                s = regexReplace("<" + tag + "(\\s[^>]*)?/>", "", s);
            }
            return s;
        }

        private string processTag(string s)
        {
            // ending tags
            Match m = P_END_TAG.Match(s);
            if (m.Success)
            {
                string name = m.Groups[1].Value.ToLower();
                if (allowed(name))
                {
                    if (!inArray(name, vSelfClosingTags))
                    {
                        if (vTagCounts.ContainsKey(name))
                        {
                            vTagCounts[name] = vTagCounts[name] - 1;
                            return "</" + name + ">";
                        }
                    }
                }
            }


            // starting tags
            m = P_START_TAG.Match(s);
            if (m.Success)
            {
                string name = m.Groups[1].Value.ToLower();
                string body = m.Groups[2].Value;
                string ending = m.Groups[3].Value;

                //debug( "in a starting tag, name='" + name + "'; body='" + body + "'; ending='" + ending + "'" );
                if (allowed(name))
                {
                    string params1 = "";

                    MatchCollection m2 = P_QUOTED_ATTRIBUTES.Matches(body);
                    MatchCollection m3 = P_UNQUOTED_ATTRIBUTES.Matches(body);
                    List<string> paramNames = new List<string>();
                    List<string> paramValues = new List<string>();
                    foreach (Match match in m2)
                    {
                        paramNames.Add(match.Groups[1].Value); //([a-z0-9]+)
                        paramValues.Add(match.Groups[3].Value); //(.*?)
                    }
                    foreach (Match match in m3)
                    {
                        paramNames.Add(match.Groups[1].Value); //([a-z0-9]+)
                        paramValues.Add(match.Groups[3].Value); //([^\"\\s']+)
                    }

                    string paramName, paramValue;
                    for (int ii = 0; ii < paramNames.Count; ii++)
                    {
                        paramName = paramNames[ii].ToLower();
                        paramValue = paramValues[ii];

                        if (allowedAttribute(name, paramName))
                        {
                            if (inArray(paramName, vProtocolAtts))
                            {
                                paramValue = processParamProtocol(paramValue);
                            }
                            params1 += " " + paramName + "=\"" + paramValue + "\"";
                        }
                    }

                    if (inArray(name, vSelfClosingTags))
                    {
                        ending = " /";
                    }

                    if (inArray(name, vNeedClosingTags))
                    {
                        ending = "";
                    }

                    if (ending == null || ending.Length < 1)
                    {
                        if (vTagCounts.ContainsKey(name))
                        {
                            vTagCounts[name] = vTagCounts[name] + 1;
                        }
                        else
                        {
                            vTagCounts.Add(name, 1);
                        }
                    }
                    else
                    {
                        ending = " /";
                    }
                    return "<" + name + params1 + ending + ">";
                }
                else
                {
                    return "";
                }
            }

            // comments
            m = P_COMMENT.Match(s);
            if (!stripComment && m.Success)
            {
                return "<" + m.Value + ">";
            }

            return "";
        }

        private string processParamProtocol(string s)
        {
            s = decodeEntities(s);
            Match m = P_PROTOCOL.Match(s);
            if (m.Success)
            {
                string protocol = m.Groups[1].Value;
                if (!inArray(protocol, vAllowedProtocols))
                {
                    // bad protocol, turn into local anchor link instead
                    s = "#" + s.Substring(protocol.Length + 1, s.Length - protocol.Length - 1);
                    if (s.StartsWith("#//"))
                    {
                        s = "#" + s.Substring(3, s.Length - 3);
                    }
                }
            }
            return s;
        }

        private string decodeEntities(string s)
        {

            s = P_ENTITY.Replace(s, new MatchEvaluator(ConverMatchEntity));

            s = P_ENTITY_UNICODE.Replace(s, new MatchEvaluator(ConverMatchEntityUnicode));

            s = P_ENCODE.Replace(s, new MatchEvaluator(ConverMatchEntityUnicode));

            s = validateEntities(s);
            return s;
        }

        private string validateEntities(string s)
        {
            s = P_VALID_ENTITIES.Replace(s, new MatchEvaluator(ConverMatchValidEntities));
            s = P_VALID_QUOTES.Replace(s, new MatchEvaluator(ConverMatchValidQuotes));
            return s;
        }

        private static bool inArray(string s, string[] array)
        {
            foreach (string item in array)
            {
                if (item != null && item.Equals(s))
                {
                    return true;
                }
            }
            return false;
        }

        private bool allowed(string name)
        {
            return (vAllowed.Count == 0 || vAllowed.ContainsKey(name)) && !inArray(name, vDisallowed);
        }

        private bool allowedAttribute(string name, string paramName)
        {
            return allowed(name) && (vAllowed.Count == 0 || vAllowed[name].Contains(paramName));
        }

        private string checkEntity(string preamble, string term)
        {

            return ";".Equals(term) && isValidEntity(preamble)
                    ? '&' + preamble
                    : "&" + preamble;
        }
        private bool isValidEntity(string entity)
        {
            return inArray(entity, vAllowedEntities);
        }
        private static string ConverMatchComments(Match match)
        {
            string matchValue = "<!--" + htmlSpecialChars(match.Groups[1].Value) + "-->";
            return matchValue;
        }

        private string ConverMatchTags(Match match)
        {
            string matchValue = processTag(match.Groups[1].Value);
            return matchValue;
        }

        private string ConverMatchEntity(Match match)
        {
            string v = match.Groups[1].Value;
            int decimal1 = int.Parse(v);
            return chr(decimal1);
        }

        private string ConverMatchEntityUnicode(Match match)
        {
            string v = match.Groups[1].Value;
            int decimal1 = Convert.ToInt32("0x" + v, 16);
            return chr(decimal1);
        }

        private string ConverMatchValidEntities(Match match)
        {
            string one = match.Groups[1].Value; //([^&;]*)
            string two = match.Groups[2].Value; //(?=(;|&|$))
            return checkEntity(one, two);
        }
        private string ConverMatchValidQuotes(Match match)
        {
            string one = match.Groups[1].Value; //(>|^)
            string two = match.Groups[2].Value; //([^<]+?)
            string three = match.Groups[3].Value;//(<|$)
            return one + regexReplace(P_QUOTE, "\"", two) + three;
        }

        public bool isAlwaysMakeTags()
        {
            return alwaysMakeTags;
        }

        public bool isStripComments()
        {
            return stripComment;
        }

        class Item
        {
            public string name { get; set; }
            public List<string> parameter { get; set; }
        }

    }

在请求时对参数的内容进行过滤:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
var nHtmlFilter = new NHtmlFilter(false);
surveyPayload.PayloadContent = nHtmlFilter.filter(surveyPayload.PayloadContent);

再次请求时,已将危险代码转成HTML转义字符串的形式了

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2023-05-08,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 DotNet NB 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
暂无评论
推荐阅读
编辑精选文章
换一批
python数据分析——数据预处理
数据预处理是数据分析过程中不可或缺的一环,它的目的是为了使原始数据更加规整、清晰,以便于后续的数据分析和建模工作。在Python数据分析中,数据预处理通常包括数据清洗、数据转换和数据特征工程等步骤。
鲜于言悠
2024/03/20
1.1K0
python数据分析——数据预处理
【数据处理包Pandas】数据载入与预处理
对于数据分析而言,数据大部分来源于外部数据,如常用的 CSV 文件、 Excel 文件和数据库文件等。 Pandas 库将外部数据转换为 DataFrame 数据格式,处理完成后再存储到相应的外部文件中。
Francek Chen
2025/01/22
3640
【数据处理包Pandas】数据载入与预处理
Python数据分析之数据预处理(数据清洗、数据合并、数据重塑、数据转换)学习笔记
参考链接: Python | pandas 合并merge,联接join和级联concat
用户7886150
2020/12/26
5.9K0
数据分析与数据挖掘 - 07数据处理
Pandas是数据处理中非常常用的一个库,是数据分析师、AI的工程师们必用的一个库,对这个库是否能够熟练的应用,直接关系到我们是否能够把数据处理成我们想要的样子。Pandas是基于NumPy构建的,让以NumPy为中心的应用变得更加的简单,它专注于数据处理,这个库可以帮助数据分析、数据挖掘、算法等工程师岗位的人员轻松快速的解决处理预处理的问题。比如说数据类型的转换,缺失值的处理、描述性统计分析、数据汇总等等功能。 它不仅仅包含各种数据处理的方法,也包含了从多种数据源中读取数据的方法,比如Excel、CSV等,这些我们后边会讲到,让我们首先从Pandas的数据类型开始学起。 Pandas一共包含了两种数据类型,分别是Series和DataFrame,我们先来学习一下Series类型。 Series类型就类似于一维数组对象,它是由一组数据以及一组与之相关的数据索引组成的,代码示例如下:
马一特
2020/09/24
2.7K0
数据分析与数据挖掘 - 07数据处理
Python数据分析模块 | pandas做数据分析(二):常用预处理操作
在数据分析和机器学习的一些任务里面,对于数据集的某些列或者行丢弃,以及数据集之间的合并操作是非常常见的. 1、合并操作 pandas.merge pandas.merge(left, right, how=’inner’, on=None, left_on=None, right_on=None, left_index=False, right_index=False, sort=False, suffixes=(‘_x’, ‘_y’), copy=True, indicator=False) 作用:通过执
用户1332428
2018/03/09
1.8K0
Python数据分析模块 | pandas做数据分析(二):常用预处理操作
Python数据分析常用模块的介绍与使用
在当今数字化时代,数据分析已经变得不可或缺。而Python,作为一种通用编程语言,其丰富的库和强大的功能使得它成为数据分析领域的佼佼者。Python数据分析模块,正是这一领域的核心组成部分,为数据科学家和工程师提供了强大的武器库。
鲜于言悠
2024/05/09
4420
Python数据分析常用模块的介绍与使用
猿创征文|数据导入与预处理-第3章-pandas基础
pandas的官网地址为:https://pandas.pydata.org/ 官网首页介绍了Pandas,
用户2225445
2022/11/12
14.2K0
猿创征文|数据导入与预处理-第3章-pandas基础
Python数据分析-pandas库入门
pandas 提供了快速便捷处理结构化数据的大量数据结构和函数。自从2010年出现以来,它助使 Python 成为强大而高效的数据分析环境。pandas使用最多的数据结构对象是 DataFrame,它是一个面向列(column-oriented)的二维表结构,另一个是 Series,一个一维的标签化数组对象。
嵌入式视觉
2022/09/05
3.9K0
Python数据分析-pandas库入门
python数据分析万字干货!一个数据集全方位解读pandas
说到python与数据分析,那肯定少不了pandas的身影,本文希望通过分析经典的NBA数据集来系统的全方位讲解pandas包,建议搭配IDE一遍敲一边读哦。话不多说,开始吧!
TechFlow-承志
2020/03/05
7.5K0
python数据分析万字干货!一个数据集全方位解读pandas
针对SAS用户:Python数据分析库pandas
Python部落(python.freelycode.com)组织翻译,禁止转载,欢迎转发。
程序员小助手
2020/04/08
12.7K0
数据导入与预处理-课程总结-04~06章
数据经过采集后通常会被存储到Word、Excel、JSON等文件或数据库中,从而为后期的预处理工作做好数据储备。数据获取是数据预处理的第一步操作,主要是从不同的渠道中读取数据。Pandas支持CSV、TXT、Excel、JSON这几种格式文件、HTML表格的读取操作,另外Python可借助第三方库实现Word与PDF文件的读取操作。本章主要为大家介绍如何从多个渠道中获取数据,为预处理做好数据准备。
用户2225445
2022/11/18
13.3K0
数据导入与预处理-课程总结-04~06章
Python数据分析--Pandas知识
利用drop_duplicates()函数删除数据表中重复多余的记录, 比如删除重复多余的ID.
py3study
2020/01/19
1.1K0
Python数据分析--Pandas知识
数据分析之Pandas缺失数据处理
3. 缺失数据的运算与分组 3.1. 加号与乘号规则 3.2. groupby方法中的缺失值 4. 填充与剔除 4.1. fillna方法 4.2. dropna方法 5. 插值
Datawhale
2020/07/06
1.7K0
数据分析之Pandas缺失数据处理
Python 数据分析(PYDA)第三版(二)
NumPy,即 Numerical Python,是 Python 中最重要的数值计算基础包之一。许多提供科学功能的计算包使用 NumPy 的数组对象作为数据交换的标准接口之一。我涵盖的关于 NumPy 的许多知识也适用于 pandas。
ApacheCN_飞龙
2024/05/24
4640
Python 数据分析(PYDA)第三版(二)
Python数据分析的数据导入和导出
数据分析的数据的导入和导出是数据分析流程中至关重要的两个环节,它们直接影响到数据分析的准确性和效率。在数据导入阶段,首先要确保数据的来源可靠、格式统一,并且能够满足分析需求。这通常涉及到数据清洗和预处理的工作,比如去除重复数据、处理缺失值、转换数据类型等,以确保数据的完整性和一致性。
鲜于言悠
2024/05/12
7300
Python数据分析的数据导入和导出
python数据分析——数据分类汇总与统计
数据分类汇总与统计是指将大量的数据按照不同的分类方式进行整理和归纳,然后对这些数据进行统计分析,以便于更好地了解数据的特点和规律。
鲜于言悠
2024/03/20
1.4K0
python数据分析——数据分类汇总与统计
python数据分析——数据分类汇总与统计
推荐一个网站给想要了解或者学习人工智能知识的读者,这个网站里内容讲解通俗易懂且风趣幽默,对我帮助很大。我想与大家分享这个宝藏网站,请点击下方链接查看。 https://www.captainbed.cn/f1
鲜于言悠
2025/03/08
7591
python数据分析——数据分类汇总与统计
数据导入与预处理-课程总结-01~03章
备注:本文主要是课程总结,不做过多的拓展,如果需要详细了解,可以查看本专栏系列内容,专栏链接直达
用户2225445
2022/11/18
3.2K0
数据导入与预处理-课程总结-01~03章
Pandas数据结构:Series与DataFrame
在数据分析领域,Python 的 Pandas 库因其强大的数据操作功能而广受欢迎。Pandas 提供了两种主要的数据结构:Series 和 DataFrame。本文将从基础概念出发,逐步深入探讨这两种数据结构的使用方法、常见问题及解决方案。
Jimaks
2024/12/17
2460
基于pandas数据预处理基础操作
# -*- coding: utf-8 -*- import numpy as np import pandas as pd #一、创建数据 #1.通过传递一个list对象来创建一个Series,pandas会默认创建整型索引 s = pd.Series([1,3,np.nan,5,8]) #2.通过传递一个numpy array,时间索引以及列标签来创建一个DataFrame dates = pd.date_range('20170301',periods = 6) df1 = pd.DataFram
hankleo
2020/09/17
7710
推荐阅读
相关推荐
python数据分析——数据预处理
更多 >
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
本文部分代码块支持一键运行,欢迎体验
本文部分代码块支持一键运行,欢迎体验