Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/340.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_Json_Pandas_Dataframe - Fatal编程技术网

Python 如何向数据框添加列并将所有行设置为特定值

Python 如何向数据框添加列并将所有行设置为特定值,python,json,pandas,dataframe,Python,Json,Pandas,Dataframe,尝试 在读取一个大型json文件并仅捕获'text'列之后,我想向dataframe添加一列,并将所有行设置为特定值: df = pd.read_json('xl-1542M.train.jsonl', lines=True, encoding='utf8').text df.replace(to_replace=[r"\\t|\\n|\\r", "\t|\n|\r"], value=["",""], regex=T

尝试

在读取一个大型json文件并仅捕获
'text'
列之后,我想向dataframe添加一列,并将所有行设置为特定值:

df = pd.read_json('xl-1542M.train.jsonl', lines=True, encoding='utf8').text
df.replace(to_replace=[r"\\t|\\n|\\r", "\t|\n|\r"], value=["",""], regex=True, inplace=True)
df['class']= 1
xl-1542M.train.jsonl

{"id": 1, "text": "Germany's youngest ambassador, Frauke Petry, made startling revelations on Thursday in a career-long crusade against Islamic immigration that even two years ahead of her 37th birthday insisted she is \"still young\".\n\nPetry, who burst onto the political scene by leading the rebellion of Angela Merkel's CDU/CSU party last September, was loud on Thursday about an \"Islamisation\" of Germany that she asserted made \"everybody\" hate secularism.\n\n\"Let me say without ambiguity, Islam is not simply another religion like Christianity,\" said the rightwing populist who sits on the Christian Social Union from the Bavarian regional parliament, declining to reveal the source of her (in)complete worldview.\n\nThis was in stark contrast to her CDU/CSU party colleagues who last year slipped in the European Parliament onto the party's bid for power in response to the migrant crisis, the unending chain of wars and terrorism plaguing the Middle East, and the persecution of minorities in cities on Germany's southern border.\n\nTwo years ago, when Petry famously gave up one of her most significant vestiges of power as the interior minister to enter with a few dozen of her party peers on the very first cross-party coalition seeking to form NATO as the CSU/CSU-Greens (at that time lead by Frauke Petry) and the SPD across the German Senate made an alliance that even her own cabinet almost sabotaged \u2013 so unable was Merkel to make peace with the CSU.\n\nThe stakes are huge for keyboard adults of Petry's age and experience. She was the felon behind last year's parliamentary drubbing in the Godesberg City Opinion Quincy House in friendships with left-wing social-democrats and then with Justin Tempelhof, an open borders fanatic who represents German Greens-Merkel Trots to Brussels.\n\nPetry suggested on Thursday that she can no longer control the hatred in Germany that so easily flowed back into her party's ranks after soldiers are militarised and stoop to reading the Koran at train stations such as Munich with ticket counters silent. She said that Berlin cowed in fear of reprisals if the milestones of Qtam killers were calledisen spiritle point signal inside every church through which they strangled eight people in Berlin.\n\nHowever, at the same time she cited U.S. Attorney General Jeff Sessions' December 2016 conviction of a network of alleged Muslim Brotherhood operatives in Birmingham for plotting to murder law enforcement officers, wonders about Islam, said that had long since passed that the numbers of North African Islam moderately recidivists of the mill muslims had dropped \u2014 The Berliner Zeitung reported.\n\nThe comments were particularly surprising considering Petry now boasts the fearlessness to create public an open defiance in what is called a Ratlines Gang, where apocalyptic non-stop propaganda has been injected into church through crowds at weekly services.\n\nPetry now heads a centre-right bloc with Jens Spahn, the deputy finance minister, and Peer Steinbr\u00fcck, chief of CDU/CSU state policy portfolio in Berlin. The feeder party for politicians like Petry will likely be unthinkable without Orb\u00e1n and Dworzak calling the shots with Washington.", "length": 663, "ended": true}
{"id": 2, "text": "3Feitage is one of those organizations that has gone and agreed to occupy Greater Boston with an event they're calling June Resistance. They're assigning each piece of property in the city the urbanist artist Robert Hack to paint. Along the way you can catch a glimpse of how sketchy Tim Turing's insanity made cyberspace.\n\nThe hackathon is this Thursday, June 13th. Lawns from all around the city will be turned into coliseums of work dedicated to the vantage point of a perceived enemy who Quake's Matrix 5 II pitches as \" Dreesyear \" or \"IN SRPD\" (Immediate Reaction Teams, made up of Detroit Police), in the image below. There's also a fort built out of Dreesyear artwork upstaged and in constant danger that anyone entering it risks \"getting SWOLEED\", soon followed by a break in the fence from an unknown criminal in the background.\n\nBut don't worry: the most badass LEGO team out there comes from the DCS community.\n\nCheck out the location page here (in the meantime, Shepard Fairey lives in Brookline and has no idea what he is doing).", "length": 238, "ended": true}
{"id": 3, "text": "Settlers hook Bayint\u00edp lawyer dead, say Ahosaurs\n\nQueensland RCMP said it had \"information\" tying Sandra Jackson, missing since last week, to the tragic murder of a Bayint\u00edp lawyer.\n\nPolice were called to the Rocko Creek apartments near the Central Queensland town of Mundubbera about 5:30 p.m. on the evening of September 4, where they made the gruesome discovery of Jackson's charred body sitting in an ashtray.\n\n\"I was in a box with my life,\" she told local journalists before she was thought to have been taken to the hospital.\n\nJust over a month after the defendant hired reactionary Qinetiq to believe she had provided evidence for her client, Yolanda Sharrocks, in the Burleigh Road civil trial, Queensland Court of Appeal Justice Paul Bhagic agreed with the ruling of in chambers 2012 to hang Jackson for the murder of Kathy Jackson.\n\nAttorneys for Jackson and Sharrocks will appear before the Court of Appeal this week in relation to the $30 million civil claim.\n\nIbrahim Al-Iraqi, a Walgett lawyer turned businessman and a patron of Saharas committee, was in court on May 5.\n\nGrisly discovery\n\nThe burnt body of three-month-old Joseph Sharrocks Jr. lay in a foetal position in another overturned guard . . . .\n\nFisheries officers said Jackson had blood around the revolver's chamber, but were unable to find the gun.\n\nShe was clutching a pair of scissors and being served a summons for possessing alcohol, when she was found. . . .\n\nA \"mask on fire,\" she was then halved in the head as police were suffering from water poisoning.\n\nRangati Malayi correspondent: Will it be a 'sale' as I said in April?\n\nKu Rabbi: Nedan Sorjedor isnt a Jew\n\nNedan Sorjedor said: People to me thought Nedan was Jewish but he is not. He meaned any type of human being. You could class Nedan as gay, lesbian, female, male or shemale. Especially with his working hours. He used to be very busy during the week and during the weekend he does have a time when he has a couple of hours off the work. So he would leave early in the morning but he would probably gather a couple or two meals and stuff. But the fact is we do not see him very often and other than that I dont see him much . . .\n\nKu Rabbi: As far as post and marriage, is she really happy with Hedifal'\n\nSorce says Nedan is a person who has Jewish traditions within his family; it makes me feel really happy to see him relieve on the role of boss for Nedan. You can see Hedifal' becoming a tyrant. Nedan will be like Zayan Ziamani \u2013 only with a lower middle name.\n\nWhat we saw from Hedifal' and Nedan was the race of the character to get into a suit and tie and give his address at the end of the movie OR everything will be taken straight from Wikivoyage. 'Welcome to Skaringden\u2026' Fish on the stove. Coffee maker. Lamp. Plush toy. A thought bubble for Nedan.\n\nKu Rabbi: Sephardic Ashkenazi gentleman\n\nSephardic Ashkenazi gentleman I think the change isn't too bad. Its becomes more than just 'settlers'. The change is more universal. It will seem more like 'litmus test questions' and I think it will be a positive move.\n\nTalat Mazer: Xiangma i teqa' ii fi\u1e93t\n\nZhengguo Si Kuuseri wiek\n\nAmEx 'It seems there are other ethnicities in China.'\n\nNewcomer Huiyin in the West simply kept pointing to the Porcelain Steel Empire [a long forgotten brand known to be central to lomoilanism while we turned our attention to the Shengshi's's heavy reliance on steelwork and trucks], which example. This, forced upon us by assistants. They generally tried to challenge yanyunnu in a formal manner to give you bits of information.\n\nWe all become Waldorf schooled in analysis fever, mixed with genes don't somebody resistuilitating Twelvegger variation results in Waldorf education?\n\nQ Gurumurti: Kyoeijuan Menggu Kimkwe Weer made toilets prevail\n\nKu Rabbi: Are people not allowed to take video cameras outside anymore?\n\nYasmin Heshy Klugu: Objective BoxHoed\n\nThis exit window was just on the floor, it was discovered on the 6th floor ceiling and outside. I was in a club with 8 friends all of us were heading out of the club after", "length": 1024, "ended": false}
{"id": 4, "text": "MPRA/FP/3W standard, also known as IEC 60529-1 time code, has four kinds of time codes - M, LHA, SJT & TWT. The time resolution of each mass scale is one tenth (T1.5) to one five tenth (T1.5T0.5) of a second. The time codes are grouped according to their phases. PMRA/FP volume-charge, IEC 69811 M/V/I ratio and M/V/I/C space charge are grouped into multiples of one minute, IEC 60436 M/V/C ratio between one hour and two hours and IEC 60529-1 time code between four and five hours.\n\nHope you will find these little notes useful !\n\nNotes\n\nThe use of Approximate ISEC code to define the combined standing wave voltage and additive electric field of individual compression pulses was superseded recently by iTron. Slow pulse trains are denoted by a pi/e.770 prefix. The punched Elemental systems assuming loop circuit 9-D are denoted by a pi/0.6 prefix\n\nDVD-ROM and Flash-ROM. Temporally stable either type is probably the best option for measuring the magnetic field non-adiabatically and reducing the complete loss of data.\n\nHere is the list of time codes posted on the MRFS web sites:", "length": 294, "ended": true}
{"id": 5, "text": "The party says they have a plan to increase the power of the city's \"most stable representative\" over the urban food system.\n\nThe last time candidates' debates took place in Toronto, about a year ago, the faces of mayoral frontrunners Olivia Chow and John Tory were mostly off-stage. Less than half of the debate subjects were discussed by NDP candidate David Soknacki and Liberal candidate Denzil Minnan-Wong.\n\nThis time around, the mayoral candidates were more involved, engaging in a strong exchange involving Sicilian Lemontorporationvest\u00f2 MD HP development consultant Stephen Carter, who regularly names ecosystem issues Mikele Perronk\u00f2 MPP and council candidate and urban advocate Fred Eisenberger in the debate, and policy analyst Bob Rennie, whose voter outreach issues netted him 1.3 million votes (60 per cent) in the 2014, 2011, and 2008 municipal elections.\n\nEsoteric Jiddan Will Ouellette, who backs the private-sector-created McLennan station individual management corporation (MMPC), not only objects to the popular narrative over who's the best park trustee, he also thinks we let a Richmond actor out skate to become chair of a county-owned Vancouver transit\n\nsystem, Richard Huelg, use social media to defend a dubious sewage by-product business deal he tried to get a lease on, and is seen along with campaign manager Gareth Cadman \"I've never seen as much crap in journalism,\" in his Toronto South community.\n\nThe debate also came just days after Chong himself showed up in campaign mode personally knocking on doors in Humber Village and one of the two wards in Toronto where Tory has said he did not even know about his own alma mater's Liberal candidate.\n\nBut our politicians don't spend a lot of time dealing with the important stuff. Enter former OPP commissioner Howard Wetlow, a long-term political roleholder. Wetlow landed an interview with us, of course, to help us get the most from the debate with only a sort-of-scholarly grasp of the format.\n\nCheating?\n\n\"One minute we'll be discussing about the PSAC, the kitchen sink issues, fighting for good jobs, and the next minute someone will be talking about pesticides and the Bell regulation,\" he said, just as inevitably as it's often said. Wetlow has served as a Toronto board member of an OPP union affiliated constituency lobby corporation, has been part of Conservative pro-industry lobbying operations, and is a longtime aide to former mayor Mel Lastman, in other words he's what one might call a typical Urban Democratic Ottawa insider.\n\nYet the reason we're curious about Waterloo unrest and the debate is because Wetlow actually went to the core of the leading contenders' platforms and identified key policy areas that they would put their power behind.\n\nHe said it's possible no candidate could go far enough in cleaning up this \u2013 our city's infrastructure projects. He says it's definitely possible no candidate could go far enough on affordability issues, and we'd like to hear what candidates would do on that one.\n\nWe'll run a series of those questions in an upcoming question-and-answer column. A plausible answer: you have absolutely nothing to worry about.\n\nBut we also have to acknowledge Toronto, and people in Toronto, don't know about all these green agenda blemp-bloop news items about taxation . . . most home owners don't even have access to EQC's new online filing system. Clearly, you don't even know about the 911 policy dispute, which is not really about service delivery, but has been fired-up by this violent immigrant-bashing video (which is full of a bunch of dog bites that appears to have been inflicted by one of the leftists).\n\nAnd we can't really get a response out of either Soknacki or Tory on just which security they would put at city correctional facilities. They're far more similar in terms of the approaches they'd take with the human rights commission or the TTC budget. Who cares about Weir Walk?\" How about Kimmie Dunn electoral campaigns? How about protecting Canadian boxer Preston Brown from us? And we really don't know what sensible election tactics any of these candidates would use to address scourge of slums,\" Downtown Chair Jean Quan kickstarted.\n\nPrizes?\n\n\"Handout having any effects on ratepayers's rent,\" David Soknacki exclaimed as he cast his vote in favour of an complaints fold-up. There was a marginally incredulous pause in responses.\n\nWhen the discussion pivoted to Rob Ford's infamous annexation of Toronto - including such changes to improvements like Greenwood and High Park as allowing him his own slice of turf -he shrugged it off, clearly insulted with suggestions that he might have done it for political reasons.\n\n\"I don't know why assessment of fealty should interfere,\" he said. When councillors suggested it's part of being mayor \"there is", "length": 1024, "ended": false}
{"id": 6, "text": "The European railway sector is receiving a pummelling as British government eurosceptics seize on a report showing that the EU-IMF bailout crisis has hardened the continent's financial landscape. Because there is no EU budget obligation to fund train lines, EU funds have been diverted to other countries' rail networks.\n\nAnd because there is no EU binding requirement to share cost better with cleaners, cleaning staff can now be filmed as they are sacked.\n\nTalks between lenders and national profiteering agencies are taking place in volume hoping to pick up the shortfall. Angry operators will protest against the unfairness of years of state handouts to companies that have secured rail contracts, and unions \u2013 already in crisis, though subsidised by taxpayers \u2013 will warn that their influence is pressured by politicians on all sides. December's European elections could change things.\n\nThe Olso Network in Finland \u2013 the nation's fourth major identity-regulated railway \u2013 narrowly escaped international aid when a major operator, OOO, defaulted in October.\n\nBecause the Spanish state has so far refused the rescue loan from its EU partners, Alstom, Italy's Trasportfrancisco or Spain's Al&A \u2013 two major operators \u2013 have all pursued national governments for support as crucial routes like London's Northern and Eurostar operated suspended in the first half of 2009.\n\nItalian interior minister Giulio Tremonti reckons that closing the railways right through the winter football tournament will help the country transfer \u20ac4bn (\u00a32.4bn) for the next four years to regional administration, and it has 5,000 to 6,000 cleaners covering around 100,000 stations.\n\nTrains will run mostly, but in emergencies diversions will be made with one possibility the diversion via Oldham or Bristol instead of the up to \u00a31bn forgone on a single train by DLR with the path of East and West England franchise \u2013 thanks to the architectural beauty of Scotland stopping trains in Denmark at Swinford centre instead of stops around Glasgow \u2013 on ice.\n\nIn December, Spain is hoping to shore up its double-A five-and-a-half year legacy scheme to bolster the daily venture of Califeque on hundreds of lines beyond Madrid.\n\nThis ragged push follows the usual route between Greece, Italy and Spain to control London British Rail's routes. The government favours the Dutch opposite \u2013 of and for himself. Permanent solution might come no country shorter than from the Peanuts comic strip, in which \"Mr Squeezy\" loses his job as manager of a landscape gardening chain and wins jobs as a fisherman. Bob Anderson, proprietor of the M&M's chain, has learned to blend thrive with loss that started with lack of investment shortly after his grandfather had died ten years earlier and wartime maintenance cut right to the bone. Anderson now pocket \u00a355m, down from \u20ac300m, thanks to a batch of loans built up by his company during his postwar reconstruction.\n\nBritish ministers want to devote their last week in office to European Union problems, before the prospect of a returning Labour government opens up Europe to hornswoggling by politicians who might want to hold proposals up through running surpluses, and foreign wild beasts \u2013 not least German Chancellor Angela Merkel's \u2013 to thrash. With two years left for the upcoming European elections, \"this reparatory session, getting rid of it as soon as possible, will make it very positive for the British way of negotiating, diplomatically\", says future business minister Tony Davies.\n\nAnticipating the level of opposition to further EU-backed conductors, Dominic Cummings, leader of the Liberal Democrats, is also hoping:\n\n\"The markets are being tackled by the question of the deleveraging of economies, which means if you are saying that you are unambiguously pro-European, you have to courteously and effectively convince [the public] that it is a pro-European government. I was in Poland and saw that the targets Elmar Brok, the Minister of Economy, had set out were the economic targets he'd set out. I would have spoken up if they would have said 'in large part, Elmar set ourselves that today'.\"\n\nDeath and Destruction\n\nMortgage packs of prime-time TV bulletins round the world are highlighting the immediate blow with years in many cases in movie and a complicated road ahead, as investment in Thailand's underwater motorway sector messes with the sterling and wages before giving way to gripes about inefficiently ruled countryside wage systems, and too time-averse firms swatting down risks with artificial unemployment.\n\nThe admittedly low-profile Chinese new year presence way beyond Beijing has Russian president Leonid Kuchma and his hardline Federal Development Cooperation Service not long ago approving another 2.5km stretch of the Don River corridor \u2013 complete with new myriad amputees in server of the canal's project manufacturer. The decision outraged Feng Zhu, founder of Blind village, one of the groups that were ignored the first time", "length": 1024, "ended": false}
{"id": 7, "text": "It's just known that he was on his back he was beating, he was choking, and there were puke all over his face, and they then, I believe, grabbed the costume and left him there.\n\n\nI'm just trying to take it all in, trying to figure out how this could happen, and why nobody tried to get to help this guy, which obviously hero.", "length": 79, "ended": true}
{"id": 8, "text": "All right, man we've talked about this your entire day. We all felt this way watching the Sandra Bland \"Approval\" video and scrolling through the commotion; feeling the anger and sadness salsa danced around in people's sexism, racism tweets and trial balloons. We just felt like we weren't doing enough. And finally, I wrote this in early June but never posted it, so its time to make it known, Bacon Madness, that Murray Rothbard is RAD and we want nerdy-list even though we are brown people with nerdy brains!\n\nAnyone else feeling what I'm going to fill later with bits of metal gear?\n\nOf all the electronic stuff, music and confederate flag material I have, my most beloved and realized collectible now is the boxed bar of pulp story we call X-211. In the world I live in, there aren't very many X-s to be found, but when I found X-211, I got very, very happy very fast. NOT that I would have sold it to anyone else; it's just that its hard to find collectible fan letters, period. x211 may very well be the most precious thing in my house. Or mine*. I struggle with the emotion of being sad about this, too.\n\nWhile the investigation and eventual exoneration of 45-year-old Sandra Bland continues, unlike that of Johannes Mehserle, named #1 dominating triggering preservation curriculums Horrifyingly Today, we are supposed to feel bad for cops. Not bad enough because it's possible you or someone you love could get killed in someone else's home by an idiotized superior unit acting in the place of a \"deep compassion for humanity that actually swells my heart\" (make of that what you will) and not to dwell too deep on a botched interrogation, we're better prepared to stand horrified at the murder of a sayonara black young man as if it could happen to us:\n\nBlack woman killed by an officer during struggle in South Carolina\n\nMicah Fromuth's daughter the victim of his police harassment\n\nTeam Black Lives Matter: one to kill me \u2014 Dana Loesch, radio host and enemy Fascist(?) ally! \u2014 No, really, this is real!\n\nRace-hustling cop. Black. On September 21, a police officer ends Eric Garner's life, using an illegal chokehold. Just after the man's lungs collapse, he is ribbed, mercilessly mocked and facilitated with a final righteous slap and mob-enraged screams birthed out as more whites join the cruelty against this black man (we all know the usual clich\u00e9s about cops and minorities because we assiduously paid attention in primary and high school followed by crime reporting as a reporter).\n\nBlacks are more likely to be killed by angry types online, then they are white (with blacks second only to black crime victims); more likely to be arrested for whatever the cops bring up their noses; more likely to be struck and hard with their own weapons; more likely to be the unwitting hunted when people of color are shooting at cops; more likely to be called a racial slur before killing or maiming unarmed people identified as blacks; more likely to be buried or cremated by an angry mob unless they kneel down and intone that the killer is trapped inside an animal body that shares cause with the person they have killed; less likely to actually be killed or injured by officers; more likely to be lynched, gassed, and beaten in most spots in America; less likely to have property confiscated or ravaged by the state's war on weed. Phew.\n\nThese blessings repeat most eloquently for black men. Again, we hear of Trayvon when white nepotism acted as an outlet for black bodies destroyed by police, followed by the various sad stories of black men hunted down, attacked, killed and enraged by one-dimensional little criminals being believed by prosecutors and juries as justification to knock some sense back in the world. Surely all this is random; surely these tragedies all happen insofar as a defense of preserves the debates oveleeening kitsch sessions in suburban houses and sun-bathed supermarkets mired in ignorance and blaseness.\n\nBut, still, black people lose 17 black people since this Attorney General, in a telling correspondence with his lawyers, excuses Darren Wilson by claiming, \"Mr. Wilson is not aware of this, but he was trained to disarm and not use force.\"\n\nLong live Reddit, this joy-inducing currency of technical scientific sanity!", "length": 934, "ended": true}
...
我已尝试保存文件以检查输出是否符合预期:

df.to_csv("test", sep='\t')
输出:

然而,预期的风险似乎并未发生,而是包含:

class 1
预期的

我希望输出如下(理想情况下没有任何列或行编号):


问题是您的
read_json(..).text
行返回的是一个序列,而不是数据帧

添加到_frame()
并引用下一行中的列可以解决此问题:

df = pd.read_json('xl-1542M.train.jsonl', lines=True, encoding='utf8').text.to_frame()
df['text'].replace(to_replace=[r"\\t|\\n|\\r", "\t|\n|\r"], value=["",""], regex=True, inplace=True)
df['class'] = 1
df = pd.read_json('xl-1542M.train.jsonl', lines=True, encoding='utf8').text.to_frame()
df['text'].replace(to_replace=[r"\\t|\\n|\\r", "\t|\n|\r"], value=["",""], regex=True, inplace=True)
df['class'] = 1